I need to be able to write some text automatically inside an image. According to the image lightness, the script must write in white or black.
So how do I check the lightness/darkness of an image with Imagick?
I need to be able to write some text automatically inside an image. According to the image lightness, the script must write in white or black.
So how do I check the lightness/darkness of an image with Imagick?
You could do something like this:
// 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);
If you want to do undercoloured text, per Fred's suggestion, you can do that in PHP with:
$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');
You could also just create a text image on some background color and overlay that on the image. Or use -undercolor with -draw or -annotate. That way, you do not have to worry about the color of the image. Or you could specify the region where you want to write text over, then get the average lightness of that region. Then test if the region is brighter or darker than mid-gray. If brighter, then create a text image of the same size with transparent background and use black text color. Similarly if darker, use white text color. So in ImageMagick command line, these would be:
Input:
Pink Undercolor:
convert logo.png \
\( -size 110x -background pink -font ubuntu-bold -fill $textcolor label:"Testng" \) \
-gravity northwest -geometry +395+400 -compose over -composite result3.png
Testing (dark region) - Unix syntax:
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
Testing (bright region):
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
Sorry, I do not know Imagick. So someone else may need to help on that.