Python将webp字节流转换为jpg字节流

2022-11-20 11:01:16

webp图片格式转jpg

  • 传入参数webp字节流
  • 返回jpg字节流
from PILimport Imagefrom ioimport BytesIOimport logging# import requestsdefchange_webp_to_jpg(webp_content):"""
    将webp图片格式转换为jpg格式
    :param webp_content: webp图片字节流
    :return: jpg图片字节流
    """
    jpg_content=""try:if webp_content.upper().startswith(b"RIF"):
            im= Image.open(BytesIO(webp_content))if im.mode=="RGBA":
                im.load()
                background= Image.new("RGB", im.size,(255,255,255))
                background.paste(im, mask=im.split()[3])
                im= background
            img_byte= BytesIO()
            im.save(img_byte,format='JPEG')
            jpg_content= img_byte.getvalue()except Exceptionas err:
        logging.error(err)return jpg_contentif jpg_contentelse webp_content## # 第一种本地图片直接转换# with open("code.webp", "rb") as f:#     jpg_binary = change_webp_to_jpg(f.read())#     with open("code.jpg", "wb") as fp:#         fp.write(jpg_binary)## # 第二种url响应的图片# url = "webp的url图片"# headers = {}# resp = requests.get(url, headers=headers)# jpg_binary = change_webp_to_jpg(resp.content)# with open("code.jpg", "wb") as fp:#     fp.write(jpg_binary)
  • 作者:十一姐
  • 原文链接:https://blog.csdn.net/weixin_43411585/article/details/107787613
    更新时间:2022-11-20 11:01:16