Todos los productos
Search
Centro de documentos

Object Storage Service:Guarde imágenes procesadas

Última actualización: Sep 01, 2026

De forma predeterminada, Object Storage Service (OSS) procesa las imágenes de origen según los parámetros de las solicitudes de procesamiento de imágenes (IMG), pero no guarda las imágenes resultantes. Si desea mostrar los mismos resultados de procesamiento, como miniaturas, imágenes recortadas o imágenes con formato convertido, puede guardar las imágenes procesadas. Para guardar una imagen procesada como un objeto en un bucket específico, agregue el parámetro saveas a la solicitud IMG.

Notas

  • Permisos obligatorios

    Para guardar una imagen procesada, debe contar con el permiso oss:PostProcessTask en el bucket de origen, así como con los permisos oss:PutBucket en el bucket de destino y oss:PutObject en el objeto de destino.

  • Regiones de almacenamiento

    Puede guardar la imagen procesada en el mismo bucket donde se almacena la imagen de origen o en uno diferente. No obstante, tanto el bucket de origen como el de destino deben pertenecer a la misma cuenta de Alibaba Cloud y encontrarse en la misma región.

  • Método de almacenamiento

    Al usar un SDK para guardar imágenes procesadas, los datos se procesan en el servidor de OSS y la imagen resultante se escribe directamente en el bucket especificado. No es necesario descargar la imagen a su dispositivo local para volver a cargarla. Agregue el parámetro saveas para guardar la imagen procesada mediante un SDK en un bucket determinado. Para obtener más información, consulte Examples on how to save processed images by using Alibaba Cloud SDKs. Tenga en cuenta que no se admite guardar directamente los resultados de procesamiento de una URL de archivo en un bucket específico. Se recomienda guardar la imagen procesada en su dispositivo local y posteriormente cargarla en el bucket correspondiente.

  • ACL

    La lista de control de acceso (ACL) de la imagen procesada es idéntica a la del bucket donde se guarda la imagen y no se puede personalizar.

  • Duración de almacenamiento

    Si desea ajustar la duración de almacenamiento de la imagen procesada, configure una política de caducidad adecuada mediante lifecycle rules.

Operaciones

Use Alibaba Cloud SDKs

El siguiente código muestra ejemplos de cómo guardar imágenes procesadas mediante los SDK de OSS para lenguajes de programación comunes. Para obtener más información sobre cómo guardar imágenes procesadas con otros SDK, consulte SDK overview.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.GenericResult;
import com.aliyun.oss.model.ProcessObjectRequest;
import java.util.Formatter;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Do not include the bucket name in the full path. 
        String sourceImage = "exampleimage.png";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // Call the shutdown method to release resources when the OSSClient is no longer in use. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Resize the image to a height and width of 100 pixels. 
            StringBuilder sbStyle = new StringBuilder();
            Formatter styleFormatter = new Formatter(sbStyle);
            String styleType = "image/resize,m_fixed,w_100,h_100";
            // Name the processed image example-resize.png and save the image to the bucket in which the source image is stored. 
            // Specify the full path of the object. Do not include the bucket name in the full path. 
            String targetImage = "example-resize.png";
            styleFormatter.format("%s|sys/saveas,o_%s,b_%s", styleType,
                    BinaryUtil.toBase64String(targetImage.getBytes()),
                    BinaryUtil.toBase64String(bucketName.getBytes()));
            System.out.println(sbStyle.toString());
            ProcessObjectRequest request = new ProcessObjectRequest(bucketName, sourceImage, sbStyle.toString());
            GenericResult processResult = ossClient.processObject(request);
            String json = IOUtils.readStreamAsString(processResult.getResponse().getContent(), "UTF-8");
            processResult.getResponse().getContent().close();
            System.out.println(json);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;

// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "yourEndpoint";
// Set the bucket name. For example, examplebucket.
$bucket= "examplebucket";
// Set the full path of the source object. For example, exampledir/exampleobject.jpg. The full path cannot include the bucket name.
$object = "exampledir/exampleobject.jpg";
// Set the full path of the destination object. For example, example-new.jpg.
$save_object = "example-new.jpg";

function base64url_encode($data)
{
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

$config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);
// If the source image is not in the specified bucket, upload the image to the bucket.
// $ossClient->uploadFile($bucket, $object, "D:\\localpath\\exampleobject.jpg");

// Resize the image to a fixed width and height of 100 px, and then rotate it 90 degrees.
$style = "image/resize,m_fixed,w_100,h_100/rotate,90";

$process = $style.
           '|sys/saveas'.
           ',o_'.base64url_encode($save_object).
           ',b_'.base64url_encode($bucket);

// Name the processed image example-new.png and save it to the current bucket.
$result = $ossClient->processObject($bucket, $object, $process);
// Print the processing result.
print($result);
const OSS = require('ali-oss');

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before you execute the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the name of your bucket.
  bucket: 'yourbucketname'
});

const sourceImage = 'sourceObject.png';
const targetImage = 'targetObject.jpg';
async function processImage(processStr, targetBucket) {
  const result = await client.processObjectSave(
    sourceImage,
    targetImage,
    processStr,
    targetBucket
  );
  console.log(result.res.status);
}

// Resize the image and configure the destination bucket that is used to save the processed image.
processImage("image/resize,m_fixed,w_100,h_100", "target bucket")

// Crop the image and configure the destination bucket that is used to save the processed image.
processImage("image/crop,w_100,h_100,x_100,y_100,r_1", "target bucket")

// Rotate the image and configure the destination bucket that is used to save the processed image.
processImage("image/rotate,90", "target bucket")

// Sharpen the image and configure the destination bucket that is used to save the processed image.
processImage("image/sharpen,100", "target bucket")

// Add watermarks to the image and configure the destination bucket that is used to save the processed image.
processImage("image/watermark,text_SGVsbG8g5Zu-54mH5pyN5YqhIQ", "target bucket")

// Convert the format of the image and configure the destination bucket that is used to save the processed image.
processImage("image/format,jpg", "target bucket")
# -*- coding: utf-8 -*-
import os
import base64
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of the bucket. 
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)

# Specify the name of the bucket in which the source image is stored. 
source_bucket_name = 'srcbucket'
# Specify the name of the bucket in which you want to save the processed image. The bucket must be within the same region as the bucket in which the source image is stored. 
target_bucket_name = 'destbucket'
# Specify the name of the source image. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: example/example.jpg. 
source_image_name = 'example/example.jpg'

# Resize the image to 100 × 100 pixels. 
style = 'image/resize,m_fixed,w_100,h_100'
# Specify the name of the processed image. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg. 
target_image_name = 'exampledir/example.jpg'
process = "{0}|sys/saveas,o_{1},b_{2}".format(style, 
    oss2.compat.to_string(base64.urlsafe_b64encode(oss2.compat.to_bytes(target_image_name))),
    oss2.compat.to_string(base64.urlsafe_b64encode(oss2.compat.to_bytes(target_bucket_name))))
result = bucket.process_object(source_image_name, process)
print(result)
// fromBucket and toBucket specify the source and destination bucket names.
// fromObjectKey and toObjectKey specify the source and destination object names. The names must be full paths that include the file extension, for example, abc/efg/123.jpg.
// action specifies the image processing operation, such as "image/resize,m_lfit,w_100,h_100".
ImagePersistRequest request = new ImagePersistRequest(fromBucket,fromObjectKey,toBucket,toObjectKey,action);

        OSSAsyncTask task = oss.asyncImagePersist(request, new OSSCompletedCallback<ImagePersistRequest, ImagePersistResult>() {
            @Override
            public void onSuccess(ImagePersistRequest request, ImagePersistResult result) {
                // Success callback
                log.i("info", "Success");
            }

            @Override
            public void onFailure(ImagePersistRequest request, ClientException clientException, ServiceException serviceException) {
              // The request failed.
              if (clientException != null) {
                  // A client-side exception occurred, such as a network error.
                  clientException.printStackTrace();
              }
              if (serviceException != null) {
                  // A server-side exception occurred.
                  Log.e("ErrorCode", serviceException.getErrorCode());
                  Log.e("RequestId", serviceException.getRequestId());
                  Log.e("HostId", serviceException.getHostId());
                  Log.e("RawMessage", serviceException.getRawMessage());
              }
            }
        });
package main

import (
	"encoding/base64"
	"fmt"
	"os"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func HandleError(err error) {
    fmt.Println("Error:", err)
    os.Exit(-1)
}

func main() {
    // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
    }

    // Create an OSSClient instance. 
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint. 
    // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. Specify the actual region.
    clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    clientOptions = append(clientOptions, oss.Region("yourRegion"))
    // Specify the version of the signature algorithm.
    clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    client, err := oss.New("yourEndpoint", "", "", clientOptions...)
    if err != nil {
	    HandleError(err)
    }

    // Specify the name of the bucket in which the source image is stored. Example: srcbucket. 
    bucketName := "SourceBucketName"
    bucket, err := client.Bucket(bucketName)
    if err != nil {
    HandleError(err)
    }
    // Specify the name of the source image. If the source image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: example/example.jpg. 
    sourceImageName := "yourObjectName"
    // Specify the name of the bucket to which you want to store the processed image. The bucket must be located in the same region as the bucket in which the source image is stored. 
    targetBucketName := "TargetBucketName"
    // Specify the name of the processed image. If the processed image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg. 
    targetImageName := "TargetObjectName"
    // Resize the image to 100 x 100 pixels and save the image to a specific bucket. 
    style := "image/resize,m_fixed,w_100,h_100"
    process := fmt.Sprintf("%s|sys/saveas,o_%v,b_%v", style, base64.URLEncoding.EncodeToString([]byte(targetImageName)), base64.URLEncoding.EncodeToString([]byte(targetBucketName)))
    result, err := bucket.ProcessObject(sourceImageName, process)
    if err != nil {
    HandleError(err)
    } else {
    fmt.Println(result)
    }
}
OSSImagePersistRequest *request = [OSSImagePersistRequest new];
// Specify the name of the bucket in which the source image is stored. 
request.fromBucket = @"srcbucket";
// Specify the name of the source image. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/src.jpg. 
request.fromObject = @"exampledir/src.jpg";
// Specify the name of the bucket that stores the processed image. The bucket must be located in the same region as the bucket in which the source image is stored. 
request.toBucket = @"destbucket";
// Specify the name of the processed image.
request.toObject = @"exampledir/dest.jpg";
// Proportionally resize the image to a width of 100 pixels and save the processed image to the specified bucket. 
request.action = @"image/resize,w_100";
// request.action = @"resize,w_100";
OSSTask * getTask = [client imageActionPersist:request];

[getTask continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
    return nil;
}];
// [getTask waitUntilFinished];
#include <alibabacloud/oss/OssClient.h>
#include <sstream>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the bucket name, for example, examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the name of the source image. If the image is not in the root directory of the bucket, include the full path, for example, example/example.jpg. */
    std::string SourceObjectName = "example/example.jpg";
    /* Specify the name of the processed image. If the image is not in the root directory of the bucket, include the full path, for example, exampledir/example.jpg. */
    std::string TargetObjectName = "exampledir/example.jpg";

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* Resize the image to a fixed width and height of 100 px and save it to the current bucket. */
    std::string Process = "image/resize,m_fixed,w_100,h_100";
    std::stringstream ss;
    ss  << Process 
    <<"|sys/saveas"
    << ",o_" << Base64EncodeUrlSafe(TargetObjectName)
    << ",b_" << Base64EncodeUrlSafe(BucketName);
    ProcessObjectRequest request(BucketName, SourceObjectName, ss.str());
    auto outcome = client.ProcessObject(request);
    if (outcome.isSuccess()) {
    std::cout << "Image processed successfully." << std::endl;
    } else {
    std::cout << "Failed to process image. Error code: " << outcome.error().Code()
              << ", Message: " << outcome.error().Message()
              << ", RequestId: " << outcome.error().RequestId() << std::endl;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

Use RESTful APIs

Si su caso de uso requiere un alto nivel de personalización, puede llamar directamente a las operaciones de la API RESTful. Para llamar directamente a la API RESTful, debe incluir el cálculo de la firma en su código.

Al usar el parámetro saveas, debe incluir las siguientes opciones:

Opción

Descripción

o

Nombre del objeto con el que desea almacenar la imagen procesada. El valor de esta opción debe estar codificado en Base64 seguro para URL. Para obtener más información, consulte Watermark encoding.

b

Nombre del bucket donde desea almacenar la imagen procesada. El valor de esta opción debe estar codificado en Base64 seguro para URL. Si no se especifica esta opción, la imagen procesada se guarda en el bucket actual.

Puede usar uno de los siguientes métodos para procesar una imagen y guardar el resultado en un bucket específico:

  • El siguiente fragmento de código muestra un ejemplo de cómo configurar parámetros IMG para procesar una imagen y guardarla en un bucket específico:

    POST /ObjectName?x-oss-process HTTP/1.1
    Host: oss-example.oss.aliyuncs.com
    Content-Length: 247
    Date: Fri, 04 May 2012 03:21:12 GMT
    Authorization: OSS4-HMAC-SHA256 Credential=LTAI********************/20250417/cn-hangzhou/oss/aliyun_v4_request,AdditionalHeaders=content-length,Signature=a7c3554c729d71929e0b84489addee6b2e8d5cb48595adfc51868c299c0c218e
    
    // Proportionally resize the source image named test.jpg to a width of 100 pixels and save the processed image to the bucket named test.
    x-oss-process=image/resize,w_100|sys/saveas,o_dGVzdC5qcGc,b_dGVzdA
  • El siguiente fragmento de código muestra un ejemplo de cómo usar un estilo de imagen para procesar una imagen y guardarla en un bucket específico:

    POST /ObjectName?x-oss-process HTTP/1.1
    Host: oss-example.oss.aliyuncs.com
    Content-Length: 247
    Date: Fri, 04 May 2012 03:22:13 GMT
    Authorization: OSS4-HMAC-SHA256 Credential=LTAI********************/20250417/cn-hangzhou/oss/aliyun_v4_request,AdditionalHeaders=content-length,Signature=a7c3554c729d71929e0b84489addee6b2e8d5cb48595adfc51868c299c0c218e
    
    // Use an image style named examplestyle to process the source image named test.jpg and save the processed image to the bucket named test.
    x-oss-process=style/examplestyle|sys/saveas,o_dGVzdC5qcGc,b_dGVzdA