drqn5418 2012-11-01 23:48
浏览 485
已采纳

在具有透明背景的单色PNG图像上更改/覆盖颜色?

What I would like to be able to do is dynamically change a solid single-colored png to another color simply by inputting the desired color code without losing the transparent background. The implementations I've seen tend to be a bit sloppy, so I was wondering if anyone can give me advice on how they would implement it.

I'd be most comfortable with a PHP solution but Python works too, hell I'll even take a good canvas solution. Any advice/examples regarding this would be very much appreciated, thanks guys.

  • 写回答

3条回答 默认 最新

  • douzhaiya3968 2012-11-02 03:21
    关注

    Ordinarily I like to work in the RGB color space, but this is a case where HLS works very well. The conversion in Python is simple, by replacing the H and S and leaving L the same.

    import colorsys
    from PIL import Image
    
    def recolor(im, r, g, b):
        h, l, s = colorsys.rgb_to_hls(r/255.0, g/255.0, b/255.0)
        result = im.copy()
        pix = result.load()
        for y in range(result.size[1]):
            for x in range(result.size[0]):
                r2, g2, b2, a = pix[x, y]
                h2, l2, s2 = colorsys.rgb_to_hls(r2/255.0, g2/255.0, b2/255.0)
                r3, g3, b3 = colorsys.hls_to_rgb(h, l2, s)
                pix[x, y] = (int(r3*255.99), int(g3*255.99), int(b3*255.99), a)
        return result
    
    recolor(im_flag, 255, 0, 0).save(r'c:\temped_flag.png')
    

    originalresult with (255,0,0)

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

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探