PHP Imagemagick将灰度转换为RGB

时间:2012-06-25 12:54:56

标签: php imagemagick color-profile

我制作了一个工具,人们可以上传照片并对其进行修改,包括去饱和,从而产生灰度图像。 我使用PHP的GD库生成最终图像。

打印这些图像时,颜色显示错误,因此使用Image Magick我会添加颜色配置文件。

除了已经灰度化的图像外,这个效果很好。添加了颜色配置文件,但是当我在Photoshop中打开图像时,它显示“无法使用嵌入式ICC配置文件,因为ICC配置文件无效。忽略配置文件”。 在Photoshop中,图像设置为灰度而不是RGB,因此附加的RGB配置文件是错误的。我需要它是RGB。

我正在使用以下代码添加所有可能的信息,以尝试使图像RGB:

<?php
$i = new Imagick();
$i->readimage('image.jpg');
$i->setimagetype(Imagick::IMGTYPE_TRUECOLOR);
$i->setimagecolorspace(Imagick::COLORSPACE_RGB);
$i->profileimage('icc', file_get_contents('AdobeRGB1998.icc'));
$i->writeimage($d);
$i->destroy();
?>

有谁知道如何成功将图像设置为RGB并附加个人资料?

我确实为'setImageProfile'和'profileImage'尝试了不同的方法和组合,也用于颜色空间和图像类型,但结果始终相同。

2 个答案:

答案 0 :(得分:2)

这让我觉得它被认为是真彩色图像。假设$img是包含灰度图像的Imagick对象,我检查它是否确实是灰度,然后编辑1个随机像素并通过添加或减去5个值来修改其红色值,具体取决于红色是否大于5。

<?php
if ($img->getImageType() == Imagick::IMGTYPE_GRAYSCALE)
{
    // Get the image dimensions
    $dim = $img->getimagegeometry();

    // Pick a random pixel
    $x = rand(0, $dim['width']-1);
    $y = rand(0, $dim['height']-1);

    // Define our marge
    $marge = 5;
    //$x = 0;
    //$y = 0;

    // Debug info
    echo "\r\nTransform greyscale to true color\r\n";
    echo "Pixel [$x,$y]\n";

    // Get the pixel from the image and get its color value
    $pixel = $img->getimagepixelcolor($x, $x);
    $color = $pixel->getcolor();
    array_pop($color); // remove alpha value

    // Determine old color for debug
    $oldColor   = 'rgb(' . implode(',',$color) . ')';
    // Set new red value
    $color['r'] = $color['r'] >= $marge ? $color['r']-$marge : $color['r'] + $marge;
    // Build new color string
    $newColor   = 'rgb(' . implode(',',$color) . ')';

    // Set the pixel's new color value
    $pixel->setcolor($newColor);

    echo "$oldColor -> $newColor\r\n\r\n";

    // Draw the pixel on the image using an ImagickDraw object on the given coordinates
    $draw = new ImagickDraw();
    $draw->setfillcolor($pixel);
    $draw->point($x, $y);
    $img->drawimage($draw);

    // Done, 
    unset($draw, $pixel);
}
// Do other stuff with $img here
?>

希望这有助于将来的任何人。

答案 1 :(得分:2)

@ a34z在评论中说:

  

“不知怎的,我必须让PS知道它是一张RGB图像,里面只有灰色像素或类似的东西。”

假设RGB图像甚至可以包含“灰色”像素,这是一个基本错误!

RGB图像的像素总是由3种颜色组合 R ed + G reen + B lue。这些是可用的3个频道,不再有。 RGB中没有灰色通道。

使RGB图像看起来灰色的原因是3个数字通道值中的每一个都相等或不太严格,至少“足够相似”。当然,也有软件可以分析3个通道的颜色值,并告诉你哪些像素是“灰色”。 ImageMagick的直方图输出会很高兴地告诉你你会说哪种灰色阴影,并为那些灰色使用不同的名称。但不要被这个颜色名称所迷惑:像素仍将由具有相同(或非常相似)强度的3种颜色组成,ImageMagick也会报告这些值。

如果你真的需要一个纯灰度图像(它只使用一个通道用于灰度级,而不是三个),那么你必须将它转换为这样的图像类型。

这两张图片看起来可能看起来一样(如果转换是正确完成的,如果您的显示器已经过校准,如果您没有红绿盲) - 但它们的内部文件结构不同。

RGB图像需要处理RGB(如果有)的ICC配置文件,例如sRGB。对于灰度,您不能使用sRGB,在那里您可能想要使用DeviceGray或其他东西......

相关问题