python-3.x - 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)
虽然它真的很混乱。有人可以帮助我吗?样本:
解决方案
推荐阅读
- javascript - JavaScript 处理和事件监听器
- regex - 如何使用 sed 或 awk 提取子字符串
- android - 在 Android 上运行 Apps 脚本?
- ruby-on-rails - gcloud app deploy 在 2.4.2 和 2.5.1 的 ruby-build 上失败
- sql - 根据SQL中的确定参数确定的行数
- javascript - Fill table with json data
- c# - Unity C# Saved Game via Binary Formatting not retaining Data
- javascript - Can't locate on device's local storage nativescript file-system generated directory
- angular - 表格Angular 5的显示微调器
- php - checkdnsrr 找不到我的域,而 dns_get_record 可以找到它