You need to enable JavaScript to run this app.
导航

基础图片处理(Python SDK)

最近更新时间2024.02.04 18:31:08

首次发布时间2023.10.12 11:15:42

TOS 支持对存储的图片进行处理,包括图片缩放、图片裁剪、图片水印、格式转换等图片处理操作。本文介绍如何通过 TOS Python SDK 进行基础图片处理。

注意事项

  • 原图格式仅支持 JPG、PNG、BMP、GIF、WEBP 和 TIFF。
  • 原图大小不能超过 20MB。
  • 原图宽、高不能超过 30000 px,总像素不能超过 2.5 亿 px(旋转操作的原图宽、高不能超过 4096 px)。
  • 缩放后的图片宽、高不能超过 16384 px,总像素不能超过 16777216 px。

示例代码

以下代码展示如何将图片高度固定为 100px,图片格式转换为 JPG 格式,然后将图片命名为 temp.jpg,并下载到本地。

import os
import tos
from tos.enum import TierType
from tos.models2 import RestoreJobParameters

# 从环境变量获取 AK 和 SK 信息。
ak = os.getenv('TOS_ACCESS_KEY')
sk = os.getenv('TOS_SECRET_KEY')
# 填写 Bucket 所在区域对应的 Endpoint。如果以华北2(北京)为例,则 your endpoint 填写为 tos-cn-beijing.volces.com,your region 填写为 cn-beijing。
endpoint = "your endpoint"
region = "your region"
bucket_name = "bucket-test"
image_key = "image.png"
file_name = "temp.jpg"
style = "image/resize,h_100/format,jpg"  # 将图片高度固定为 100px 并转为 JPG 格式

try:
    # 创建 TosClientV2 对象,对桶和对象的操作都通过 TosClientV2 实现。
    client = tos.TosClientV2(ak, sk, endpoint, region)
    client.get_object_to_file(bucket=bucket_name, key=image_key, process=style, file_path=file_name)
except tos.exceptions.TosClientError as e:
    # 操作失败,捕获客户端异常,一般情况为非法请求参数或网络异常。
    print('fail with client error, message:{}, cause: {}'.format(e.message, e.cause))
except tos.exceptions.TosServerError as e:
    # 操作失败,捕获服务端异常,可从返回信息中获取详细错误信息。
    print('fail with server error, code: {}'.format(e.code))
    # request id 可定位具体问题,强烈建议日志中保存。
    print('error with request id: {}'.format(e.request_id))
    print('error with message: {}'.format(e.message))
    print('error with http code: {}'.format(e.status_code))
    print('error with ec: {}'.format(e.ec))
    print('error with request url: {}'.format(e.request_url))
except Exception as e:
    print('fail with unknown error: {}'.format(e))

相关文档

关于图片处理的详细介绍,请参见图片处理概述