【发布时间】:2018-02-18 12:05:57
【问题描述】:
我需要能够在图像中自动写入一些文本。根据图像的亮度,脚本必须用白色或黑色书写。
那么如何使用 Imagick 检查图像的明暗度?
【问题讨论】:
标签: php image imagemagick imagick
我需要能够在图像中自动写入一些文本。根据图像的亮度,脚本必须用白色或黑色书写。
那么如何使用 Imagick 检查图像的明暗度?
【问题讨论】:
标签: php image imagemagick imagick
您也可以在某些背景颜色上创建一个文本图像并将其覆盖在图像上。或者将 -undercolor 与 -draw 或 -annotate 一起使用。这样,您就不必担心图像的颜色。或者您可以指定要在其中写入文本的区域,然后获取该区域的平均亮度。然后测试该区域是否比中灰色更亮或更暗。如果更亮,则创建具有透明背景的相同大小的文本图像并使用黑色文本颜色。同样,如果较暗,请使用白色文本颜色。所以在 ImageMagick 命令行中,这些将是:
输入:
粉红色底色:
convert logo.png \
\( -size 110x -background pink -font ubuntu-bold -fill $textcolor label:"Testng" \) \
-gravity northwest -geometry +395+400 -compose over -composite result3.png
测试(暗区)- Unix 语法:
test=`convert logo.png -crop 110x36+395+400 +repage -colorspace gray -format "%[fx:(mean>0.5)?1:0]" info:`
if [ $test -eq 1 ]; then
textcolor="black"
else
textcolor="white"
fi
convert logo.png \
\( -size 110x -background none -font ubuntu-bold -fill $textcolor label:"Testng" \) \
-gravity northwest -geometry +395+400 -compose over -composite result1.png
测试(亮区):
test=`convert logo.png -crop 110x36+100+400 +repage -colorspace gray -format "%[fx:(mean>0.5)?1:0]" info:`
if [ $test -eq 1 ]; then
textcolor="black"
else
textcolor="white"
fi
convert logo.png \
\( -size 110x -background none -font ubuntu-bold -fill $textcolor label:"Testng" \) \
-gravity northwest -geometry +100+400 -compose over -composite result2.png
对不起,我不知道 Imagick。所以其他人可能需要在这方面提供帮助。
【讨论】:
你可以这样做:
// Load the image
$imagick = new Imagick("image.jpg");
// convert to HSL - Hue, Saturation and LIGHTNESS
$imagick->transformImageColorspace(imagick::COLORSPACE_HSL);
// Get statistics for the LIGHTNESS
$Lchannel = $imagick->getImageChannelMean(imagick::CHANNEL_BLUE);
$meanLightness = $Lchannel['mean']/65535;
printf("Mean lightness: %f",$meanLightness);
如果您想根据 Fred 的建议制作底色文本,您可以在 PHP 中使用:
$image = new Imagick("image.jpg");
$draw = new ImagickDraw();
$draw->setFillColor('#ffffff');
$draw->setFontSize(24);
$draw->setTextUnderColor('#ff000080');
$image->annotateImage($draw,30,50,0,"Undercoloured Text");
$image->writeImage('result.jpg');
【讨论】:
cropImage() 将其裁剪到他想要添加文本的区域,然后在该选定的裁剪区域上运行统计信息。