代码之家  ›  专栏  ›  技术社区  ›  London Smith

IMagick检查亮度图像

  •  2
  • London Smith  · 技术社区  · 8 年前

    我需要能够在图像中自动写入一些文本。根据图像亮度,脚本必须用白色或黑色书写。

    那么,如何使用Imagick检查图像的明暗度?

    2 回复  |  直到 7 年前
        1
  •  3
  •   Mark Setchell    8 年前

    您可以这样做:

    // 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');
    

    enter image description here

        2
  •  2
  •   fmw42    8 年前

    您也可以在一些背景色上创建一个文本图像,并将其覆盖在图像上。或者使用-底色和-绘制或-注释。这样,您就不必担心图像的颜色。或者您可以指定要在其中写入文本的区域,然后获得该区域的平均亮度。然后测试该区域是否比中灰色亮或暗。如果更亮,则创建一个具有透明背景的相同大小的文本图像,并使用黑色文本颜色。同样,如果颜色较深,请使用白色文本颜色。所以在ImageMagick命令行中,这些将是:

    输入:

    enter image description here

    粉色底色:

    convert logo.png \
    \( -size 110x -background pink -font ubuntu-bold -fill $textcolor label:"Testng" \) \
    -gravity northwest -geometry +395+400 -compose over -composite result3.png
    

    enter image description here

    测试(暗区)-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
    

    enter image description here

    测试(亮区):

    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
    

    enter image description here

    对不起,我不认识Imagick。所以其他人可能需要帮助。