我正在尝试使用 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 时指定图像填充颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!