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 时指定图像填充颜色


基础教程推荐
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01