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

时间:2019-10-21 10:42:18

标签: python python-imaging-library color-profile

我编写了一个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

2 个答案:

答案 0 :(得分:0)

我认为打开和读取图像时会出现问题,请尝试使用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)

您在image_data变量中以RGB模式保存了您的图片,或将其用于进一步处理

答案 1 :(得分:0)

  

profile = image.info.get("icc_profile", ""),然后在使用参数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