【发布时间】:2015-12-28 23:19:54
【问题描述】:
我用 PHP 编写了这个函数,用于将图片从一种颜色变为另一种颜色,我非常喜欢它。对我来说,它看起来非常逼真,并且似乎很好地考虑了原始图像的亮度。但是,它很慢。使用我正在使用的图像尺寸,重新着色一张图像大约需要 23 秒。我知道减速带来自循环遍历每个像素,所以我通过 Imagick 类尝试了 Imagemagick 函数的一些不同组合,但我找不到任何我喜欢我的函数结果的组合。有没有办法,也许使用 C,我可以把它写成 Imagemagick 的某种插件,甚至通过 Imagick 类使它可用,这样我就不必通过像 exec() 这样的东西来运行它?我也尝试过使用 Imagick 的 PixelIterator,并查看了 fxImage,但这些都一样慢,如果不是更糟的话。
public function colorize($img, $rgb) {
imagealphablending($img, true);
imagesavealpha($img, true);
// get width and height of image
$iwidth = imagesx($img);
$iheight = imagesy($img);
// loop through each pixel
for ($y=0; $y<$iheight; $y++) for ($x=0; $x<$iwidth; $x++) {
// get all original r, g, b, a values of the pixel
$orgb = imagecolorat($img, $x, $y);
$oa = ($orgb >> 24) & 0xFF;
$or = ($orgb >> 16) & 0xFF;
$og = ($orgb >> 8) & 0xFF;
$ob = $orgb & 0xFF;
// add up orginal rgb values and new rgb values
$total_original = $or + $og + $ob;
$total_new = $rgb[0] + $rgb[1] + $rgb[2];
// adjust brightness using average of rgb channels
$bright = -127 + $total_new/3;
// take average difference between new color's brightness and old color's brightness, add brightness adjustment to it, and round
$adjustment = round($bright + ($total_new - $total_original) / -3);
// set each channel to new color channels, add the adjustment, and make sure the result isn't less than 0 or greater than 255
$r = max(0,min($adjustment + $rgb[0],255));
$g = max(0,min($adjustment + $rgb[1],255));
$b = max(0,min($adjustment + $rgb[2],255));
// replace original pixel
$nrgb = imagecolorallocatealpha($img, $r, $g, $b, $oa);
imagesetpixel($img, $x, $y, $nrgb);
}
}
【问题讨论】:
-
您能否提供一个示例图像/RGB 值用于您的基准测试?
标签: php image-processing imagemagick gd imagick