Specify image filling color when rotating in python with PIL and setting expand argument to true(使用 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 时指定图像填充颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 PIL 在 python 中旋转并将扩展参数设置为 true 时指定图像填充颜色


基础教程推荐
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01