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

基础图片处理(Node.js SDK)

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

首次发布时间2023.12.19 18:47:28

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

注意事项

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

示例代码

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

// 导入 SDK, 当 TOS Node.JS SDK 版本小于 2.5.2 请把下方 TosClient 改成 TOS 导入
import { TosClient, TosClientError, TosServerError } from '@volcengine/tos-sdk';

// 创建客户端
const client = new TosClient({
  accessKeyId: process.env['TOS_ACCESS_KEY'],
  accessKeySecret: process.env['TOS_SECRET_KEY'],
  region: "Provide your region", // 填写 Bucket 所在地域。以华北2(北京)为例,则 "Provide your region" 填写为 cn-beijing。
  endpoint: "Provide your endpoint", // 填写域名地址
});

function handleError(error) {
  if (error instanceof TosClientError) {
    console.log('Client Err Msg:', error.message);
    console.log('Client Err Stack:', error.stack);
  } else if (error instanceof TosServerError) {
    console.log('Request ID:', error.requestId);
    console.log('Response Status Code:', error.statusCode);
    console.log('Response Header:', error.headers);
    console.log('Response Err Code:', error.code);
    console.log('Response Err Msg:', error.message);
  } else {
    console.log('unexpected exception, message: ', error);
  }
}

const bucketName = 'node-sdk-test-bucket';
async function main() {
  try {
    // 原图名称
    const imageKey = 'image.png';
    // 保存至文件
    const fileName = 'temp.jpg';
    // 请求并增加数据处理
    const style = 'image/resize,h_100/format,jpg'; /* 将图片高度固定为 100px,并转为 JPG 格式 */
    const { requestId, headers } = await client.getObjectToFile({
      bucket: bucketName,
      key: imageKey,
      process: style,
      filePath: fileName,
    });
    console.log('getObjectToFile Request ID: ', requestId);
    console.log('ContentType: ', headers['content-type']);
  } catch (error) {
    handleError(error);
  }
}

main();

相关文档

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