You need to enable JavaScript to run this app.
文档中心
文档控制台
注册
对象存储

对象存储

复制全文
下载 pdf
图片处理
图片处理持久化(Python SDK)
复制全文
下载 pdf
图片处理持久化(Python SDK)

TOS 默认不保存处理后的图片。您可以使用代码将处理后的图片保存至指定的存储桶。本文介绍如何通过 TOS Python SDK 将处理后的图片保存至指定存储桶。

注意事项

  • 使用图片处理持久化的账号必须拥有原图所在桶的读权限,图片转存的目标桶的写权限。
  • 使用匿名用户将处理后的图片保存至指定的存储桶时,该存储桶必须为公共写权限。
  • 原图所在桶与图片转存的目标桶必须属于同一地域。
  • 转存图片的访问权限默认为私有,存储类型默认为标准存储。

示例代码

以下代码展示如何将图片高度固定为 100px,图片格式转换为 JPG 格式,然后将处理后的图片命名为 temp.jpg,并保存至目标存储桶。

import base64
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"
style = "image/resize,h_100/format,jpg"
save_bucket = "your destination bucket name"
save_object = "temp.jpg"

try:
    # 创建 TosClientV2 对象,对桶和对象的操作都通过 TosClientV2 实现。
    client = tos.TosClientV2(ak, sk, endpoint, region)
    object_stream = client.get_object(
        bucket=bucket_name,
        key=image_key,
        process=style,
        save_bucket=base64.b64encode(save_bucket.encode("utf-8")).decode("utf-8"),
        save_object=base64.b64encode(save_object.encode("utf-8")).decode("utf-8"),
    )
    print(object_stream.read())
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))

相关文档

关于图片处理持久化的详细介绍,请参见图片处理持久化

最近更新时间:2024.12.24 15:47:13
这个页面对您有帮助吗?
有用
有用
无用
无用