2011-09-22 131 views
17

我一直用這種方法將頭撞到牆上,所以也許有人可以幫忙。PIL中的透明PNG原來並不透明

我使用PIL打開一個PNG透明背景和一些隨機黑色塗鴉,並試圖把它放在另一個PNG(沒有透明度),然後將其保存到第三個文件。

它在最後出來黑色,這是令人煩惱的,因爲我沒有告訴它是黑色的。

我已經用其他帖子提出的多個修復程序進行了測試。圖像以RGBA格式打開,並且仍然混亂。

此外,該程序應該處理各種文件格式,這就是爲什麼我使用PIL。具有諷刺意味的是,我嘗試過的第一種格式全是扭曲的。

任何幫助,將不勝感激。這裏是代碼:

from PIL import Image 
img = Image.open(basefile) 
layer = Image.open(layerfile) # this file is the transparent one 
print layer.mode # RGBA 
img.paste(layer, (xoff, yoff)) # xoff and yoff are 0 in my tests 
img.save(outfile) 
+0

http://stackoverflow.com/questions/5324647/how-to-merge-a-transparent-png-image-with-another-的可能的複製image-using-pil –

回答

30

我想你想要使用的是粘貼掩碼參數。 看到docs,(向下滾動到paste

from PIL import Image 
img = Image.open(basefile) 
layer = Image.open(layerfile) # this file is the transparent one 
print layer.mode # RGBA 
img.paste(layer, (xoff, yoff), mask=layer) 
# the transparancy layer will be used as the mask 
img.save(outfile) 
+3

Bravo! PIL文檔並不清楚面具是什麼 - 首先我認爲它是一個數字(因爲他們說'如果面具是0,如果面具是255'),那麼我認爲它就像盒子參數,而是用於確定圖像參數的哪個部分將被複制。現在它更有意義,謝謝! – MarkTraceur

+0

你非常幫助我。謝謝 – imkost

+8

哦爲什麼地球上它不會默認做這個... – Claudiu