【问题标题】:IMagick check lightness imageIMagick 检查亮度图像
【发布时间】:2018-02-18 12:05:57
【问题描述】:

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

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

【问题讨论】:

    标签: php image imagemagick imagick


    【解决方案1】:

    您也可以在某些背景颜色上创建一个文本图像并将其覆盖在图像上。或者将 -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。所以其他人可能需要在这方面提供帮助。

    【讨论】:

      【解决方案2】:

      你可以这样做:

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

      【讨论】:

      • 我很惊讶,解决方案看起来如此简单。认为那会复杂得多。非常感谢。
      • 它可以变得更复杂。如果您的图像具有三分之二的天空和黑暗的地面,并且您在地面上有文字,则需要文字灯;但是整个图像的平均值可能会说使用深色文本?在这种情况下,您需要文本所在的亮度。
      • @Bonzo 你说得很好。如果这是一个问题,OP 可以复制图像并使用cropImage() 将其裁剪到他想要添加文本的区域,然后在该选定的裁剪区域上运行统计信息。
      猜你喜欢
      • 2011-06-20
      • 2014-07-18
      • 1970-01-01
      • 1970-01-01
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      相关资源
      最近更新 更多