Skip to content

Instantly share code, notes, and snippets.

@merthmagic
Last active August 25, 2023 05:06
Show Gist options
  • Select an option

  • Save merthmagic/e848dfb85b2b045058c3d94f10db734d to your computer and use it in GitHub Desktop.

Select an option

Save merthmagic/e848dfb85b2b045058c3d94f10db734d to your computer and use it in GitHub Desktop.
convert WEBP image to PNG format and resize if necessary
from PIL import Image
def webp_to_png(input_path, output_path, size=None):
# 打开webp文件
img = Image.open(input_path)
if size is None:
pass
# 重新调整图片的大小
else:
img = img.resize(size, Image.ANTIALIAS)
# 转换为RGBA模式
img = img.convert("RGBA")
# 获取图片的数据
datas = img.getdata()
new_data = []
for item in datas:
# 改变所有白(也近似于白)色像素点为透明
if item[0] > 200 and item[1] > 200 and item[2] > 200:
new_data.append((255, 255, 255, 0))
else:
new_data.append(item)
# 更新图片数据
img.putdata(new_data)
# 保存为png文件
img.save(output_path, 'PNG')
if __name__ == '__main__':
webp_to_png("d:\\tencent-cloud.webp", "d:\\t.png", (180, 148))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment