Python将tiff转换成png

文章介绍了如何使用Python的PIL库将Base64编码的image/tiff格式图片转换为image/png格式,同时提供了解决页面展示问题的方法,以及如何进行图片压缩,包括直接转换和按比例缩放的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

base64 的 image/tiff 无法在页面直接展示,将其转换为 image/png




解决方案

from io import BytesIO

from PIL import Image

with Image.open('a.tiff') as image:
    bytesIO = BytesIO()
    image.save(bytesIO, format='PNG', quality=75)
    img = bytesIO.getvalue()
    with open('a.png', 'wb') as f:  # 写入图片
        f.write(img)




压缩并转换

from io import BytesIO

from PIL import Image

with Image.open('a.tiff') as image:
    width, height = image.size
    target_width = 500  # 目标宽度
    if width > target_width:
        height = round(target_width * height / width)
        width = target_width
        size = (width, height)
        image = image.resize(size)

    bytesIO = BytesIO()
    image.save(bytesIO, format='PNG', quality=75)
    img = bytesIO.getvalue()
    with open('a.png', 'wb') as f:  # 写入图片
        f.write(img)




直接转换

from PIL import Image

Image.MAX_IMAGE_PIXELS = None  # 防止报错PIL.Image.DecompressionBombError


def tif_to_png(input_path, output_path, width=1000):
    """

    :param input_path: tif文件路径
    :param output_path: 导出文件路径
    :param width: 目标宽度
    :return:
    """
    with Image.open(input_path) as image:
        _width, _height = image.size  # 原图宽高
        height = int(width * _height / _width)  # 目标高度,等比缩放
        resize = image.resize((width, height))  # tif一般很大,等比缩放到合理大小
        resize.save(output_path, quality=75)




参考文献

  1. Image Module - Pillow Documentation
  2. Python图片按比例缩放后的宽和高(PIL等比缩放)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XerCis

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值