Convert JPG from AdobeRGB to sRGB using PIL?

后端 未结 3 1509
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-13 19:15

How can I detect if the JPG is AdobeRGB and if it is convert it in python to sRGB JPG.

If that is possible in PIL, that would be great. Thank you.

3条回答
  •  臣服心动
    2021-02-13 20:09

    Thanks for the spec link martineau, I've put some working PIL code together with functions that detect the presence of a Adobe RGB ICC profile within an Image, and convert the colorspace to sRGB.

    adobe_to_xyz = (
        0.57667, 0.18556, 0.18823, 0,
        0.29734, 0.62736, 0.07529, 0,
        0.02703, 0.07069, 0.99134, 0,
    ) # http://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf                                
    
    xyz_to_srgb = (
        3.2406, -1.5372, -0.4986, 0,
        -0.9689, 1.8758, 0.0415, 0,
        0.0557, -0.2040, 1.0570, 0,
    ) # http://en.wikipedia.org/wiki/SRGB                                                     
    
    def adobe_to_srgb(image):
        return image.convert('RGB', adobe_to_xyz).convert('RGB', xyz_to_srgb)
    
    def is_adobe_rgb(image):
        return 'Adobe RGB' in image.info.get('icc_profile', '')
    
    # alternative solution if happy to retain profile dependency:                             
    # http://stackoverflow.com/a/14537273/284164                                              
    # icc_profile = image.info.get("icc_profile")                                             
    # image.save(destination, "JPEG", icc_profile=icc_profile)
    

    (I used these to create a Django easy-thumbnails processor function):

    def preserve_adobe_rgb(image, **kwargs):
        if is_adobe_rgb(image):
            return adobe_to_srgb(image)
        return image
    

提交回复
热议问题