2017-04-25 162 views
3
from PIL import Image 
from PIL import ImageDraw 
from io import BytesIO 
from urllib.request import urlopen 

url = "https://i.ytimg.com/vi/W4qijIdAPZA/maxresdefault.jpg" 
file = BytesIO(urlopen(url).read()) 
img = Image.open(file) 
img = img.convert("RGBA") 
draw = ImageDraw.Draw(img, "RGBA") 
draw.rectangle(((0, 00), (img.size[0], img.size[1])), fill=(0,0,0,127)) 
img.save('dark-cat.jpg') 

這給了我一個巨大的黑色方塊。我希望它是一隻帶貓的半透明黑色方形。有任何想法嗎?PIL在圖像上畫一個半透明的方形覆蓋物

回答

5

顯然這不是一個錯誤,正如我原先的想法。

您可以通過創建一個臨時的圖像,並使用Image.alpha_composite()做到這一點,如下圖所示:

from PIL import Image 
from PIL import ImageDraw 
from io import BytesIO 
from urllib.request import urlopen 

url = "https://i.ytimg.com/vi/W4qijIdAPZA/maxresdefault.jpg" 
file = BytesIO(urlopen(url).read()) 
img = Image.open(file) 
img = img.convert("RGBA") 

# make a blank image for the rectangle, initialized to a completely transparent color 
tmp = Image.new('RGBA', img.size, (0,0,0,0)) 

# get a drawing context for it 
draw = ImageDraw.Draw(tmp) 

# draw a semi-transparent rect on the temporary image 
draw.rectangle(((0, 0), img.size), fill=(0,0,0,127)) 

# composite the two images together 
img = Image.alpha_composite(img, tmp) 
img.save('dark-cat.jpg') 

這裏有結果的縮小尺寸版本:

darken picture of a cat

+1

感謝您的幫助。我剛剛創建了一個新問題:https://github.com/python-pillow/Pillow/issues/2496 –

+0

@ChaseRoberts它不是一個錯誤,它是對「Draw」應該做什麼的誤解。它不會混合,它會用一組新像素替換一組像素。 [文檔中的示例](http://pillow.readthedocs.io/en/3.1.x/reference/ImageDraw.html#example-draw-partial-opacity-text)顯示這是一個兩步過程,在空白畫布上用不透明度繪圖,然後合成結果。如本答案的第二部分所示。 –

+0

@MarkRansom:事實上,我的解決方法就是這樣做(一般來說)。 – martineau

0

如果你只是想爲了使整個圖像變暗,有一種更簡單的方式:

img = Image.eval(img, lambda x: x/2)