首页 > 解决方案 > Python PIL Pillow - 将 PNG 转换为 JPG 时透明度遮罩不好

问题描述

我想将 png 图像文件转换为 jpg 并调整其大小。

我想要实现的是:(1)导入PNG文件,(2)获取文件名和扩展名,(3)将图像大小调整为1000x1000(比例调整大小方法,不拉伸到框架),(4)创建BG 1000x1000, (5)将图片放在画布中间, (6)保存为JPG

该脚本对 JPG 或其他格式(如 eps)完全有效,但总是为 PNG 抛出错误“透明蒙版错误” (并非总是如此,但有 90% 的可能性会出错)。我认为它与 alpha 通道或我不太了解的东西有关。

这是我的代码:

        #Open an Image
        dirLoadOpenFile = parentFolder + '_images\\before2\\'
        #img = Image.open(dirLoadOpenFile + importFile[i])
        try:
            img = Image.open(dirLoadOpenFile + importFile[i])
        except (FileNotFoundError): #catch an error if file doesnt exist
            errorExport = errorExport + 1
            break
            
        checkExt = importFile[i]
        checkExt = checkExt[-3:]
        
        if checkExt == "png":
            img.convert('RGBA')
            img.putalpha(255)
        else:
            img.convert('RGB')
            
        #Resizing image
        hasilResize = resize_image(img, 1000, 1000, False)

        #Creating white background 1000x1000
        white = (255, 255, 255, 255)
        background = Image.new('RGB', (1000, 1000), white)

        #Placing image on the middle (center) of canvas
        img_w, img_h = hasilResize.size
        bg_w, bg_h = background.size
        offsetMiddle = ((bg_w - img_w) // 2, (bg_h - img_h) // 2)
        
        if checkExt == "png":
            background.paste(hasilResize, offsetMiddle, mask=hasilResize)
        else:
            background.paste(hasilResize, offsetMiddle)
            
        #Saving an images
        dirLoadSaveFile = parentFolder + "_images\\after2\\"
        background.save(dirLoadSaveFile + saveFile[i], quality=100, optimize=True, progressive=True)

虽然它真的很混乱。有人可以帮助我吗?样本:

https://i.stack.imgur.com/KfJ85.png

https://i.stack.imgur.com/8qGJa.png

标签: python-3.ximage-processingpython-imaging-library

解决方案


推荐阅读