添加alpha通道时图像不会更改

2024-05-18 20:15:01 发布

您现在位置:Python中文网/ 问答频道 /正文

枕头包有一个名为^{}的方法,用于添加或更改图像的alpha通道。你知道吗

我试着使用这种方法,发现我不能改变图像的背景色。原始图像是

enter image description here

这是我添加alpha的代码

from PIL import Image

im_owl = Image.open("owl.jpg")

alpha = Image.new("L", im_owl.size, 50)
im_owl.putalpha(alpha)

im_owl.show()

生成的图像与原始图像没有什么不同。我试过用不同的alpha值,看不出有什么区别。你知道吗

可能出了什么问题?你知道吗


Tags: 方法代码from图像imageimportalphanew
3条回答

尝试保存图像并查看它。 我也不能直接从电脑上看到图像

im_owl.show()

但当我救了它

im_owl.save()

我能看到图像改变了。你知道吗

尝试使用

im_owl.save("alphadOwl.png")

然后查看保存的图像。似乎alpha通道不适用于bmp或jpg文件。它是一个bmp文件,用im.show()显示

(作为记录,我在mac上,我不知道im.show()是否在其他设备上使用不同的应用程序)。你知道吗

正如@sanyam和@Pam所指出的,我们可以保存转换后的图像并正确显示。这是因为在Windows上,在使用系统默认图像查看器显示图像之前,图像会保存为临时BMP文件,如PIL documentation

Image.show(title=None, command=None)

    Displays this image. This method is mainly intended for debugging purposes.

    On Unix platforms, this method saves the image to a temporary PPM file, and calls
    either the xv utility or the display utility, depending on which one can be found.

    On macOS, this method saves the image to a temporary BMP file, and opens it with
    the native Preview application.

    On Windows, it saves the image to a temporary BMP file, and uses the standard BMP
    display utility to show it (usually Paint).

为了解决这个问题,我们可以将枕头代码修补为使用PNG格式作为默认格式。首先,我们需要找到枕头包装的根源:

import PIL
print(PIL.__path__)

在我的系统上,输出是:

[’D:\Anaconda\lib\site-packages\PIL’]

转到这个目录并打开文件ImageShow.py。我在register(WindowsViewer)行之后添加以下代码:

    class WindowsPNGViewer(Viewer):
        format = "PNG"

        def get_command(self, file, **options):
            return ('start "Pillow" /WAIT "%s" '
                    '&& ping -n 2 127.0.0.1 >NUL '
                    '&& del /f "%s"' % (file, file))

    register(WindowsPNGViewer, -1)

在那之后,我可以用alpha通道正确地显示图像。你知道吗

参考文献

相关问题 更多 >

    热门问题