如何在使用PIL保存png时保留RGB颜色?

2024-05-19 14:14:51 发布

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

我编写了一个python程序,它将三个png图像组合成一个图像。我正在使用PIL来打开、调整大小、合并和保存生成的图像。所有的功能都在那里,但产生的图像有一个完全不同的颜色配置文件从原来的。你知道吗

我尝试了几种选择:
1我已尝试将新图像创建为“RGBA”
结果:TKinter GUI不再显示图像
2试图从原始图像复制颜色配置文件,然后在保存最终图像时使用该配置文件:
代码:profile = image.info.get("icc_profile", "")然后在使用参数icc_profile = profile保存文件时使用结果变量 结果:无变化

最小可复制代码

from PIL import Image as pImage
from tkinter.filedialog import asksaveasfilename

newImage = pImage.new('RGB', (976, 976))
background = pImage.open("Gameboy_Background.png")
screen_shot = pImage.open("screenshot.png")
cover_art = pImage.open("[coverart.png][1]")
newImage.paste(background)

w, h = screen_shot.size
newW = 875
newH = int(newW * h / w)
screen_shot = screen_shot.resize((newW, newH), pImage.ANTIALIAS)
newImage.paste(screen_shot, (50, 155))

w, h = cover_art.size
newW = 175
newH = int(newW * h / w)
cover_art = cover_art.resize((newW, newH), pImage.ANTIALIAS)
newImage.paste(cover_art, (100, 205))

file2Save = asksaveasfilename(initialdir="/", title="Select file", filetypes={("PNG files", "*.png")})
newImage.save(file2Save + ".png", "PNG")

使用的PNG图像 1https://i.stack.imgur.com/Lj1wo.png [2] :https://i.stack.imgur.com/4iauQ.png [3] :https://i.stack.imgur.com/2voFC.png

Resulting Image


Tags: 图像png配置文件coveropenprofilescreenpaste
2条回答

profile = image.info.get("icc_profile", "") then I use the resulting variable when saving the file using the argument icc_profile = profile

事实上,这对我来说似乎是正确的方法。image是截图,对吧?那就是你想复制其个人资料的人。你知道吗

from PIL import Image as pImage
from tkinter.filedialog import asksaveasfilename

newImage = pImage.new('RGB', (976, 976))
background = pImage.open("Gameboy_Background.png")
screen_shot = pImage.open("screenshot.png")
cover_art = pImage.open("coverart.png")
newImage.paste(background)

profile = screen_shot.info.get("icc_profile", "")

w, h = screen_shot.size
newW = 875
newH = int(newW * h / w)
screen_shot = screen_shot.resize((newW, newH), pImage.ANTIALIAS)
newImage.paste(screen_shot, (50, 155))

w, h = cover_art.size
newW = 175
newH = int(newW * h / w)
cover_art = cover_art.resize((newW, newH), pImage.ANTIALIAS)
newImage.paste(cover_art, (100, 205))

file2Save = "output"
newImage.save(file2Save + ".png", "PNG", icc_profile=profile)

结果:

enter image description here

我想是的,当你打开并阅读图像。试试看这将使用tkinkter gui打开和读取文件,然后使用numpy转换为数组。像这样的代码:

import tkinter as tk
from tkinter import filedialog
import numpy as np
//get ur extension as png file
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename(filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
images = Image.open(file_path)
image_data=np.asarray(image)
image_data = cv2.cvtColor(image_data, cv2.COLOR_BGR2RGB)

你有你的图像在rgb模式在图像\数据变量保存它或使用它作进一步的处理

相关问题 更多 >