今天查PIL合成圖片國內(nèi)的資料不是太復雜就是相互抄,搞股了半天也沒一個能用的麦射,用渣渣英語查了一下谷歌,秒解決小渊。
準備工作:
1: 確保兩張圖片是一個格式法褥,圖片在生成的時候, 不知道會用什么壓縮工具酬屉,會導致格式不一致半等,這是我花了好長時間才發(fā)現(xiàn)的坑,如何看格式圖片格式:
foreground= Image.open("./a.png")
background= Image.open("./b.png")
print(background)
print(foreground)
這時會打印log
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=512x512 at 0x117C249E8>
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=512x512 at 0x10AA30E48>
mode = RGBA就說明現(xiàn)在可以完美合成圖片了呐萨,這樣既可以合成透明通道部分杀饵,也可以合成普通圖片合成。
2: 圖片準備完畢就合成圖片谬擦,代碼就三行
final2 = Image.new("RGBA", background.size)
final2 = Image.alpha_composite(final2, background)
final2 = Image.alpha_composite(final2, foreground)
final2.show()
final2.save("./my.png")
圖片的合成就我這幾行代碼全部搞定切距,中文搜索圖片合成全是看不懂的天書,希望能幫到大家惨远。
借鑒文章谜悟,做一個有素質(zhì)的簡書er:
https://stackoverflow.com/questions/5324647/how-to-merge-a-transparent-png-image-with-another-image-using-pil
https://juejin.im/post/5a5c51f7f265da3e498007be