使用 PIL 在 python 中旋转时指定图像填充颜色并将扩展参数设置为 true [英] Specify image filling color when rotating in python with PIL and setting expand argument to true

查看:36
本文介绍了使用 PIL 在 python 中旋转时指定图像填充颜色并将扩展参数设置为 true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 PIL 在 Python 中旋转图像并将 expand 参数设置为 true.似乎当我的图像的背景是黑色时,保存为 bmp 的结果图像会比我的图像有白色背景时小很多,然后我用白色替换了由于扩展而导致的黑色.在任何一种情况下,我的原始图像总是两种颜色,现在我需要较小的文件大小,因为我将这些图像放在嵌入式设备上.

I'm trying to rotate an image in Python using PIL and having the expand argument to true. It seems that when the background of my image is black, the resulting image saved as a bmp will be a lot smaller than if I have a white background for my image, and then I replace the black due to expand with white. In either case, my original image is always of two colors, and right now i need the file size to be small, since I'm putting these images on an embedded device.

如果我可以在扩展时强制旋转以填充另一种颜色,或者是否有其他方法可以旋转我的图片以使其变小,有什么想法吗?

Any ideas if i can force rotate to fill in another color when expanding or if there is another way to rotate my picture in order to make it small?

推荐答案

如果您的原始图像没有 alpha 层,您可以使用 alpha 层作为蒙版将背景转换为白色.当 rotate 创建背景"时,它使其完全透明.

If your original image has no alpha layer, you can use an alpha layer as a mask to convert the background to white. When rotate creates the "background", it makes it fully transparent.

# original image
img = Image.open('test.png')
# converted to have an alpha layer
im2 = img.convert('RGBA')
# rotated image
rot = im2.rotate(22.2, expand=1)
# a white image same size as rotated image
fff = Image.new('RGBA', rot.size, (255,)*4)
# create a composite image using the alpha layer of rot as a mask
out = Image.composite(rot, fff, rot)
# save your work (converting back to mode='1' or whatever..)
out.convert(img.mode).save('test2.bmp')

这篇关于使用 PIL 在 python 中旋转时指定图像填充颜色并将扩展参数设置为 true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆