Todos los productos
Search
Centro de documentos

Object Storage Service:Procesamiento de imágenes (SDK de Browser.js)

Última actualización: Sep 05, 2026

El procesamiento de imágenes es un servicio escalable, seguro, rentable y altamente confiable que ofrece OSS. Después de cargar una imagen en OSS, puede procesarla desde cualquier dispositivo con conexión a internet mediante interfaces RESTful sencillas.

Notas de uso

  • Si utiliza herramientas de empaquetado como Webpack o Browserify, instale el SDK de OSS para Browser.js con el comando npm install ali-oss.

  • Si intenta acceder a un bucket de OSS desde un navegador sin reglas CORS configuradas, el navegador rechazará la solicitud. Por lo tanto, configure las reglas CORS del bucket antes de acceder a él desde un navegador. Para obtener más información, consulte Installation.

  • En la mayoría de los casos, el SDK de OSS para Browser.js se ejecuta dentro de navegadores. Para evitar exponer su par de AccessKey, se recomienda usar credenciales de acceso temporales obtenidas de Security Token Service (STS) al acceder a OSS.

    Las credenciales de acceso temporales incluyen un par de AccessKey y un token de seguridad. El par de AccessKey está formado por un AccessKey ID y un AccessKey secret. Para conocer cómo obtener credenciales de acceso temporales, consulte Use STS for temporary access authorization.

Procesar imágenes con parámetros de procesamiento de imágenes

Procesar una imagen con un solo parámetro de procesamiento de imágenes

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>

  <body>
    <!--Import the SDK file.-->
    <script
      type="text/javascript"
      src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
    ></script>
    <script type="text/javascript">
      const client = new OSS({
	authorizationV4: true,
        // Obtain a temporary AccessKey pair (AccessKey ID and AccessKey secret) from the STS service.
        accessKeyId: 'yourAccessKeyId',
        accessKeySecret: 'yourAccessKeySecret',
        // Obtain a security token (SecurityToken) from the STS service.
        stsToken: 'yourSecurityToken',
        refreshSTSToken: async () => {
          // Obtain temporary access credentials from your STS service.
          const info = await fetch("your_sts_server");
          return {
            accessKeyId: info.accessKeyId,
            accessKeySecret: info.accessKeySecret,
            stsToken: info.stsToken,
          };
        },
        // The interval to refresh temporary access credentials. Unit: milliseconds.
        refreshSTSTokenInterval: 300000,
        // Specify the bucket name. For example, examplebucket.
        bucket: "examplebucket",
        // Replace yourRegion with the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
        region: "yourRegion",
      });

      // Scale the image to a fixed width and height of 100 px.
      async function scale() {
        try {
          // Specify the full path of the object. For example, exampledir/exampleobject.jpg. The full path cannot contain the bucket name.
          const result = await client.signatureUrl("exampledir/exampleobject.jpg", {
            expires: 3600,
            process: "image/resize,m_fixed,w_100,h_100",
          });
          console.log(result);
        } catch (e) {
          console.log(e);
        }
      }

      scale();
    </script>
  </body>
</html>

Procesar una imagen con varios parámetros de procesamiento de imágenes

Para usar varios parámetros de procesamiento de imágenes, sepárelos con una barra diagonal (/).

!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>

  <body>
    <!--Import the SDK file.-->
    <script
      type="text/javascript"
      src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
    ></script>
    <script type="text/javascript">
      const client = new OSS({
        authorizationV4: true,
        // Obtain a temporary AccessKey pair (AccessKey ID and AccessKey secret) from the STS service.
        accessKeyId: 'yourAccessKeyId',
        accessKeySecret: 'yourAccessKeySecret',
        // Obtain a security token (SecurityToken) from the STS service.
        stsToken: 'yourSecurityToken',
        refreshSTSToken: async () => {
          // Obtain temporary access credentials from your STS service.
          const info = await fetch("your_sts_server");
          return {
            accessKeyId: info.accessKeyId,
            accessKeySecret: info.accessKeySecret,
            stsToken: info.stsToken,
          };
        },
        // The interval to refresh temporary access credentials. Unit: milliseconds.
        refreshSTSTokenInterval: 300000,
        // Specify the bucket name. For example, examplebucket.
        bucket: "examplebucket",
        // Replace yourRegion with the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
        region: "oss-cn-hangzhou",
      });

      // Scale the image to a fixed width and height of 100 px, and then rotate it by 90 degrees.
      async function resize() {
        try {
          // Specify the full path of the object. For example, exampledir/exampleobject.jpg. The full path cannot contain the bucket name.
          const result = await client.signatureUrl("exampledir/exampleobject.jpg", {
            expires: 3600,
            process: "image/resize,m_fixed,w_100,h_100/rotate,90",
          });
          console.log(result);
        } catch (e) {
          console.log(e);
        }
      }

      resize();
    </script>
  </body>
</html>

Procesar imágenes con estilos de imagen

  1. Cree un estilo de imagen.

    Un estilo admite varios parámetros de procesamiento de imágenes, lo que permite ejecutar operaciones complejas. Para obtener más información, consulte Image styles.

  2. Procese la imagen con el estilo creado.

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <title>Document</title>
      </head>
    
      <body>
        <!--Import the SDK file.-->
        <script
          type="text/javascript"
          src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
        ></script>
        <script type="text/javascript">
          const client = new OSS({
    	authorizationV4: true,
            // Obtain a temporary AccessKey pair (AccessKey ID and AccessKey secret) from the STS service.
            accessKeyId: 'yourAccessKeyId',
            accessKeySecret: 'yourAccessKeySecret',
            // Obtain a security token (SecurityToken) from the STS service.
            stsToken: 'yourSecurityToken',
            refreshSTSToken: async () => {
              // Obtain temporary access credentials from your STS service.
              const info = await fetch("your_sts_server");
              return {
                accessKeyId: info.accessKeyId,
                accessKeySecret: info.accessKeySecret,
                stsToken: info.stsToken,
              };
            },
            // The interval to refresh temporary access credentials. Unit: milliseconds.
            refreshSTSTokenInterval: 300000,
            // Specify the bucket name. For example, examplebucket.
            bucket: "examplebucket",
            // Replace yourRegion with the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
            region: "oss-cn-hangzhou",
          });
    
          // Scale the image to a fixed width and height of 100 px, and then rotate it by 90 degrees.
          async function style() {
            try {
              // Specify the full path of the object. For example, exampledir/exampleobject.jpg. The full path cannot contain the bucket name.
              const result = await client.signatureUrl("exampledir/exampleobject.jpg", {
                expires: 3600,
                // Replace yourCustomStyleName with the name of the image style that you created in Step 1.
                process: "style/yourCustomStyleName",
              });
              console.log(result);
            } catch (e) {
              console.log(e);
            }
          }
    
          style();
        </script>
      </body>
    </html>
    

Persistencia del procesamiento de imágenes

De forma predeterminada, el servicio de procesamiento de imágenes no guarda los resultados. Con la función de persistencia del procesamiento de imágenes, puede guardar la imagen procesada en el mismo bucket que contiene la imagen original.

A continuación se muestra un ejemplo de código sobre cómo usar la persistencia del procesamiento de imágenes.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>

  <body>
    <!--Import the SDK file.-->
    <script
      type="text/javascript"
      src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
    ></script>
    <script type="text/javascript">
      const client = new OSS({
	authorizationV4: true,
        // Obtain a temporary AccessKey pair (AccessKey ID and AccessKey secret) from the STS service.
        accessKeyId: 'yourAccessKeyId',
        accessKeySecret: 'yourAccessKeySecret',
        // Obtain a security token (SecurityToken) from the STS service.
        stsToken: 'yourSecurityToken',
        refreshSTSToken: async () => {
          // Obtain temporary access credentials from your STS service.
          const info = await fetch("your_sts_server");
          return {
            accessKeyId: info.accessKeyId,
            accessKeySecret: info.accessKeySecret,
            stsToken: info.stsToken,
          };
        },
        // The interval to refresh temporary access credentials. Unit: milliseconds.
        refreshSTSTokenInterval: 300000,
        // Specify the bucket name. For example, examplebucket.
        bucket: "examplebucket",
        // Replace yourRegion with the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
        region: "oss-cn-hangzhou",
      });

      // Specify the full path of the source object. For example, exampledir/src.png. The full path cannot contain the bucket name.
      const sourceImage = "exampledir/src.png";
      // Specify the full path of the destination object for the processed image. For example, exampledir/dest.png. The full path cannot contain the bucket name.
      const targetImage = "exampledir/dest.png";
      async function processImage(processStr, targetBucket) {
        const result = await client.processObjectSave(
          sourceImage,
          targetImage,
          processStr,
          targetBucket
        );
        console.log(result.res.status);
      }

      // Scale the source image to a fixed width and height of 100 px and save it to the source bucket.
      processImage("image/resize,m_fixed,w_100,h_100", "examplebucket");
    </script>
  </body>
</html>
           

Generar una URL firmada para un archivo con parámetros de procesamiento de imágenes

Cuando accede a un archivo privado mediante su URL, se requiere una firma. No es posible agregar parámetros de procesamiento de imágenes directamente a una URL firmada. Para procesar una imagen privada, incluya dichos parámetros en la firma. A continuación se muestra un ejemplo de código:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>

  <body>
    <!--Import the SDK file.-->
    <script
      type="text/javascript"
      src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
    ></script>
    <script type="text/javascript">
      const client = new OSS({
        authorizationV4: true,
        // Obtain a temporary AccessKey pair (AccessKey ID and AccessKey secret) from the STS service.
        accessKeyId: 'yourAccessKeyId',
        accessKeySecret: 'yourAccessKeySecret',
        // Obtain a security token (SecurityToken) from the STS service.
        stsToken: 'yourSecurityToken',
        refreshSTSToken: async () => {
          // Obtain temporary access credentials from your STS service.
          const info = await fetch("your_sts_server");
          return {
            accessKeyId: info.accessKeyId,
            accessKeySecret: info.accessKeySecret,
            stsToken: info.stsToken,
          };
        },
        // The interval to refresh temporary access credentials. Unit: milliseconds.
        refreshSTSTokenInterval: 300000,
        // Specify the bucket name. For example, examplebucket.
        bucket: "examplebucket",
        // Replace yourRegion with the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
        region: "oss-cn-hangzhou",
      });

      // Generate a signed URL for a file with image processing parameters and set the expiration time of the signed URL to 600s. The maximum expiration time is 32400s.
      const signUrl = client.signatureUrl("oss.png", {
        expires: 600,
        process: "image/resize,w_300",
      });
      console.log("signUrl=" + signUrl);
    </script>
  </body>
</html>