douchendan0040 2014-10-06 22:04
浏览 89
已采纳

PHP将24位颜色转换为4位颜色

Background, I am converting images to ascii art. This works perfectly and even works with 24-bit color, converting the colors to the right rgb values. However, I now want to render the ascii art in 4-bit color palette rather than 24-bit.

How do I convert 24-bit colors to 4-bit with PHP?

More specifically, I have the standard IRC color pallet which I need to convert any given Hexidecimal or RGB value to. It is preferred that the colors match as best as possible when converted to the 4-bit color.

Other ideas I have had on this are to convert the image itself to a 4-bit palette (using GD, which is what I use to read in the colors right now) before trying to grab colors off of it. And another idea might be to define a color range for each of the following color and just check that the given 24-bit color is in the range, however I wouldn't know how to get the ranges for all colors into that palette.

enter image description here

  • 写回答

4条回答 默认 最新

  • doucuo4413 2014-10-08 09:10
    关注

    In the end, despite the wonderful suggestions surrounding imagemagick I found a good solution using straight php. I was able to calculate the closest color through the use of delta E 2000 with a modified version of php-color-difference library found on github, here is my fork: https://github.com/nalipaz/php-color-difference

    The pertinent example is:

    <?php
    include('lib/color_difference.class.php');
    
    $palette = array(
      '00' => array(255, 255, 255),
      '01' => array(0, 0, 0),
      '02' => array(0, 0, 139),
      '03' => array(0, 128, 0),
      '04' => array(255, 0, 0),
      '05' => array(139, 0, 0),
      '06' => array(128, 0, 128),
      '07' => array(255, 165, 0),
      '08' => array(255, 255, 0),
      '09' => array(50, 205, 50),
      '10' => array(0, 128, 128),
      '11' => array(173, 216, 230),
      '12' => array(0, 0, 255),
      '13' => array(255, 105, 180),
      '14' => array(128, 128, 128),
      '15' => array(211, 211, 211),
    );
    
    $color_rgb = array(255, 255, 128);
    $color_delta_e = new color_difference($color_rgb);
    $match_index = $color_delta_e->getClosestMatch($palette);
    $color = $palette[$match_index];
    

    I am pretty happy with this solution and smaller amount of overhead. Thanks for the suggestions guys.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?