Todos os produtos
Search
Central de documentação

Object Storage Service:Recorte personalizado

Última atualização: Jul 03, 2026

Recorte imagens em dimensões exatas especificando largura, altura, coordenadas iniciais e posição de ancoragem.

Cenários

  • Web design: recorte imagens para ajustar elementos de layout, como avatares, planos de fundo e galerias de produtos.

  • Especificações de imagens para redes sociais: diferentes plataformas impõem requisitos específicos de tamanho para vários tipos de imagens, incluindo miniaturas, publicações e stories. Para garantir uma apresentação visual ideal, recorte as imagens previamente nas dimensões recomendadas.

  • Desenvolvimento de aplicativos móveis: recorte ícones de aplicativos, telas de abertura e gráficos internos para corresponder às diversas resoluções de dispositivos.

  • Gestão de bancos de dados de imagens: organizações como bibliotecas e arquivos que mantêm grandes repositórios precisam padronizar as dimensões das imagens por meio de recortes em tamanhos predefinidos durante os fluxos de catalogação e arquivamento.

Observações de uso

  • A largura e a altura especificadas da imagem processada não devem exceder 16.384 pixels.

  • Se as coordenadas iniciais ultrapassarem os limites da imagem original, o sistema retornará um erro BadRequest: Advance cut's position is out of image.

  • Caso a largura e a altura especificadas ultrapassem as dimensões da imagem original, a área de recorte será limitada aos contornos da imagem.

Métodos

Use URLs de objetos, SDKs do OSS ou chame operações de API para configurar parâmetros de processamento de imagens (IMG). URLs de objetos são suportadas apenas para imagens acessíveis publicamente (leitura pública ou leitura/escrita pública). Para imagens privadas, use SDKs do OSS ou chame diretamente as operações de API. Para mais informações, consulte Métodos de processamento de imagens.

Recortar imagens com leitura pública ou leitura/escrita pública

Se a ACL da imagem for leitura pública ou leitura/escrita pública, anexe parâmetros IMG à URL do objeto para acessar a imagem processada.

Neste exemplo, ?x-oss-process=image/crop,parame_value é anexado à URL de uma imagem de leitura pública. Basta substituir parame_value pelos parâmetros e valores específicos descritos na seção Parâmetros. Quando aplicável, inclua múltiplos parâmetros na URL.

URL da imagem original

URL usada para acessar a imagem processada

https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg

https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg?x-oss-process=image/crop,x_800,y_50

Recortar imagens privadas

Usar SDKs do OSS

Exemplo de código para recortar uma imagem privada com SDKs do OSS. Para outras linguagens de programação, consulte Visão geral do SDK.

Java

É necessário o OSS SDK for Java 3.17.4 ou posterior.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GetObjectRequest;
import java.io.File;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // Specify the endpoint of the region. In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the region of the endpoint. Example: cn-hangzhou. 
        String region = "cn-hangzhou";
        // 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 source image. Do not include the bucket name in the full path. 
        String objectName = "example.jpg";
        // Specify the full path of the processed image. Example: D:\\dest.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
        String pathName = "D:\\dest.jpg";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Crop an area of 900 × 900 pixels in the lower-right corner of the image. 
            String image = "image/crop,w_900,h_900,g_se";
            GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
            request.setProcess(image);
            // Save the processed image to your local computer. 
            // If you specify only the name of the processed image such as dest.jpg without specifying the local path, the processed image is saved to the local path of the project to which the sample program belongs. 
            ossClient.getObject(request, new File("D:\\dest.jpg"));
        } 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

É necessário o OSS SDK for PHP 2.7.0 ou posterior.

<?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 the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
$provider = new 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 name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";
// Specify the full path of the source image. Do not include the bucket name in the full path. 
$object = "src.jpg";
// Specify the full path of the processed image. Example: D:\\dest.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
// If you specify only the name of the processed image such as dest.jpg without specifying the local path, the processed image is saved to the local path of the project to which the sample program belongs. 
$download_file = "D:\\dest.jpg";

$config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,        
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        // Specify the ID of the Alibaba Cloud region in which the bucket is located. 
        "region" => "cn-hangzhou"
    );
$ossClient = new OssClient($config);

// Crop an area of 900 × 900 pixels in the lower-right corner of the image. 
$image = "image/crop,w_900,h_900,g_se";

$options = array(
    OssClient::OSS_FILE_DOWNLOAD => $download_file,
    OssClient::OSS_PROCESS => $image);

// Save the processed image to your local computer. 
$ossClient->getObject($bucket, $object, $options);                           

Python

É necessário o OSS SDK for Python 2.18.4 ou posterior.

# -*- coding: utf-8 -*-
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 Alibaba Cloud region in which the bucket is located. 
region = 'cn-hangzhou'
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)

# If the source image is stored in the root directory of the bucket, you can specify only the image name. Example: source-example.jpg. If the source image is not stored in the root directory of the bucket, you must specify the full path of the source image. Example: exampledir/source-example.jpg. 
key = 'source-example.jpg'

# Specify the full path of the processed image. Example: D:\\target-example.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
local_file_name = 'D:\\target-example.jpg'

# Configure the crop parameters to crop an area of 900 × 900 pixels in the lower-right corner of the image. 
process = 'image/crop,w_900,h_900,g_se'

# Use the get_object method and pass the processing instruction by using the process parameter. 
result = bucket.get_object_to_file(key, local_file_name, process=process)

Go

É necessário o OSS SDK for Go 3.0.2 ou posterior.

package main

import (
	"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. 
	client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region("cn-hangzhou"))
	if err != nil {
		HandleError(err)
	}

	// Specify the name of the bucket in which the source image is stored. Example: examplebucket. 
	bucketName := "examplebucket"
	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 source image. Example: exampledir/example.jpg. 
	sourceImageName := "example.jpg"
	// Specify the name of the processed image. 
	targetImageName := "D://dest.jpg"
	// Crop an area of 900 × 900 pixels in the lower-right corner of the image. 
	image := "image/crop,w_900,h_900,g_se"
	err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(image))
	if err != nil {
		HandleError(err)
	}
}

Usar a API do OSS

Inicie solicitações de API RESTful diretamente. Inclua o cálculo da assinatura no seu código. Para saber como calcular o cabeçalho Authorization, consulte (Recomendado) Incluir uma assinatura V4.

Especifique parâmetros de recorte na operação GetObject para recortar as imagens no tamanho exato necessário. Para mais informações, consulte GetObject.

GET /oss.jpg?x-oss-process=image/crop,w_900,h_900,g_se HTTP/1.1
Host: oss-example.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: SignatureValue

Parâmetros

Ação: crop

A tabela a seguir descreve os parâmetros para recorte de imagens.

Parâmetro

Descrição

Valor válido

w

Largura da área a ser recortada.

[0, largura da imagem]

Valor padrão: valor máximo.

h

Altura da área a ser recortada.

[0, altura da imagem]

Valor padrão: valor máximo.

x

Coordenada X da área a ser recortada. O valor padrão é a coordenada X do canto superior esquerdo da imagem.

[0, largura da imagem]

y

Coordenada Y da área a ser recortada. O valor padrão é a coordenada Y do canto superior esquerdo da imagem.

[0, altura da imagem]

g

Posição de ancoragem dentro de uma grade 3×3. A imagem é dividida em nove blocos, e a área de recorte é alinhada a uma dessas posições.

  • nw: superior esquerdo

  • north: superior central

  • ne: superior direito

  • west: centro esquerdo

  • center: centro

  • east: centro direito

  • sw: inferior esquerdo

  • south: inferior central

  • se: inferior direito

Para saber como calcular a posição de cada bloco, consulte a tabela abaixo.

A tabela a seguir mostra como as posições dos blocos são calculadas. srcW é a largura da imagem original e srcH é a altura da imagem original.

Bloco

Método de cálculo

nw

0, 0

north

srcW/2 - w/2, 0

ne

srcW - w, 0

west

0, srcH/2 - h/2

center

srcW/2 - w/2, srcH/2 - h/2

east

srcW - w, srcH/2 - h/2

sw

0, srcH - h

south

srcW/2 - w/2, srcH - h

se

srcW - w, srcH - h

Exemplos

Recortar a partir de um ponto inicial específico

Recorte uma imagem a partir do ponto inicial (800, 50) até os limites:

  • Especifique a ação: crop.

  • Defina o ponto inicial (800, 500): x_800,y_500.

  • Recorte até os limites: os valores máximos de w e h são usados por padrão para o recorte. Portanto, especificar os parâmetros w e h é opcional.

Para recortar uma imagem de leitura pública ou leitura/escrita pública, anexe ?x-oss-process=image/crop,x_800,y_500 à URL da imagem. O OSS aplica dinamicamente a operação de recorte mediante solicitação e retorna a imagem processada. Para saber como recortar uma imagem privada, consulte Recortar imagens privadas.

Demonstração

O exemplo a seguir demonstra como recortar uma imagem original a partir do ponto inicial (800, 50) até os limites, anexando ?x-oss-process=image/crop,x_800,y_500 à URL da imagem original:

Imagem original

Imagem processada

image

image

URL da imagem original: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg

URL usada para acessar a imagem processada: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg?x-oss-process=image/crop,x_800,y_500

Recortar uma área com base na largura e altura especificadas a partir de um ponto inicial específico

Recorte uma área de 300 × 300 pixels a partir do ponto inicial (800, 500):

  • Especifique a ação: crop.

  • Defina o ponto inicial (800, 500): x_800,y_500.

  • Recorte uma área de 300 × 300 pixels: w_300,h_300.

Para recortar uma imagem de leitura pública ou leitura/escrita pública, anexe ?x-oss-process=image/crop,x_800,y_500,w_300,h_300 à URL da imagem. O OSS aplica dinamicamente a operação de recorte mediante solicitação e retorna a imagem processada. Para saber como recortar uma imagem privada, consulte Recortar imagens privadas.

Resultado

A tabela a seguir demonstra o efeito da extração de uma área de 300 × 300 pixels do ponto inicial especificado (800, 500), anexando ?x-oss-process=image/crop,x_800,y_500,w_300,h_300 à URL da imagem original:

Imagem original

Imagem processada

image

image

URL da imagem original: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg

URL usada para acessar a imagem processada: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg?x-oss-process=image/crop,x_800,y_500,w_300,h_300

Recortar uma área com base na largura e altura especificadas no canto inferior direito de uma imagem

Recorte uma área de 900 × 900 pixels no canto inferior direito de uma imagem

  • Especifique a ação: crop.

  • Defina o ponto inicial no canto inferior direito: g_se.

  • Recorte uma área de 900 × 900 pixels: w_900,h_900.

Para recortar uma imagem de leitura pública ou leitura/escrita pública, anexe ?x-oss-process=image/crop,g_se,w_900,h_900 à URL da imagem. O OSS aplica dinamicamente a operação de recorte mediante solicitação e retorna a imagem processada. Para saber como recortar uma imagem privada, consulte Recortar imagens privadas.

Resultado

A tabela a seguir demonstra o efeito do recorte de uma área de 900 × 900 pixels no canto inferior direito de uma imagem, anexando ?x-oss-process=image/crop,g_se,w_900,h_900 à URL da imagem original:

Imagem original

Imagem processada

image

image

URL da imagem original: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg

URL usada para acessar a imagem processada: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg?x-oss-process=image/crop,g_se,w_900,h_900

Recortar uma área com base na largura e altura especificadas no canto inferior direito de uma imagem e esticar a área recortada

Recorte uma área de 900 × 900 pixels no canto inferior direito de uma imagem e estique a área recortada para baixo em (100.200):

  • Especifique a ação: crop.

  • Defina o ponto inicial no canto inferior direito da imagem e estique a área recortada para baixo em (100.200): g_se,x_100,y_200

  • Recorte uma área de 900 × 900 pixels: w_900,h_900.

Para recortar uma imagem de leitura pública ou leitura/escrita pública, anexe ?x-oss-process=image/crop,g_se,x_100,y_200,w_900,h_900 à URL da imagem. O OSS aplica dinamicamente a operação de recorte mediante solicitação e retorna a imagem processada. Para saber como recortar uma imagem privada, consulte Recortar imagens privadas.

Resultado

A tabela a seguir demonstra o efeito do recorte de uma área de 900 × 900 pixels no canto inferior direito de uma imagem, anexando ?x-oss-process=image/crop,g_se,x_100,y_200,w_900,h_900 à URL da imagem original:

Imagem original

Imagem processada

image

image

URL da imagem original: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg

URL usada para acessar a imagem processada: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg?x-oss-process=image/crop,g_se,x_100,y_200,w_900,h_900

Recortar uma imagem usando recorte inteligente

Configure os seguintes parâmetros para recortar uma imagem usando recorte inteligente:

  • Especifique a ação: crop.

  • Defina o algoritmo: g_auto

Antes de processar imagens com SDKs do OSS, certifique-se de que o bucket de destino esteja associado a um projeto Intelligent Media Management (IMM).

Código de exemplo

Java

É necessário o OSS SDK for Java 3.17.4 ou posterior.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GetObjectRequest;
import java.io.File;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // Specify the endpoint of the region. In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the region of the endpoint. Example: cn-hangzhou. 
        String region = "cn-hangzhou";
        // 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 source image. Do not include the bucket name in the full path. 
        String objectName = "example.jpg";
        // Specify the full path of the processed image. Example: D:\\dest.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
        String pathName = "D:\\dest.jpg";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Perform smart cropping. 
            String image = "image/crop,g_auto";
            GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
            request.setProcess(image);
            // Save the processed image to your local computer. 
            // If you specify only the name of the processed image such as dest.jpg without specifying the local path, the processed image is saved to the local path of the project to which the sample program belongs. 
            ossClient.getObject(request, new File("D:\\dest.jpg"));
        } 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

É necessário o OSS SDK for PHP 2.7.0 ou posterior.

<?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 the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
$provider = new 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 name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";
// Specify the full path of the source image. Do not include the bucket name in the full path. 
$object = "src.jpg";
// Specify the full path of the processed image. Example: D:\\dest.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
// If you specify only the name of the processed image such as dest.jpg without specifying the local path, the processed image is saved to the local path of the project to which the sample program belongs. 
$download_file = "D:\\dest.jpg";

$config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,        
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        // Specify the ID of the Alibaba Cloud region in which the bucket is located. 
        "region" => "cn-hangzhou"
    );
$ossClient = new OssClient($config);

// Perform smart cropping. 
$image = "image/crop,g_auto";

$options = array(
    OssClient::OSS_FILE_DOWNLOAD => $download_file,
    OssClient::OSS_PROCESS => $image);

// Save the processed image to your local computer. 
$ossClient->getObject($bucket, $object, $options);                           

Python

É necessário o OSS SDK for Python 2.18.4 ou posterior.

# -*- coding: utf-8 -*-
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 Alibaba Cloud region in which the bucket is located. 
region = 'cn-hangzhou'
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)

# If the source image is stored in the root directory of the bucket, you can specify only the image name. Example: source-example.jpg. If the source image is not stored in the root directory of the bucket, you must specify the full path of the source image. Example: exampledir/source-example.jpg. 
key = 'source-example.jpg'

# Specify the full path of the processed image. Example: D:\\target-example.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
local_file_name = 'D:\\target-example.jpg'

# Perform smart cropping. 
process = 'image/crop,g_auto'

# Use the get_object method and pass the processing instruction by using the process parameter. 
result = bucket.get_object_to_file(key, local_file_name, process=process)

Go

É necessário o OSS SDK for Go 3.0.2 ou posterior.

package main

import (
	"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. 
	client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region("cn-hangzhou"))
	if err != nil {
		HandleError(err)
	}

	// Specify the name of the bucket in which the source image is stored. Example: examplebucket. 
	bucketName := "examplebucket"
	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 source image. Example: exampledir/example.jpg. 
	sourceImageName := "example.jpg"
	// Specify the name of the processed image. 
	targetImageName := "D://dest.jpg"
	// Perform smart cropping. 
	image := "image/crop,g_auto"
	err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(image))
	if err != nil {
		HandleError(err)
	}
}

Resultado

A tabela a seguir demonstra o efeito da aplicação do parâmetro image/crop,g_auto e de algoritmos inteligentes para recortar a imagem:

Imagem original

Imagem processada

source image

image

Realizar um recorte de dimensão fixa centralizado no maior rosto detectado na imagem

Recorte uma área de 200 × 200 pixels centralizada no maior rosto detectado na imagem:

  • Especifique a ação: crop.

  • Recorte uma área centralizada no maior rosto detectado na imagem: g_face.

  • Recorte uma área de 200 × 200 pixels: w_200,h_200.

Antes de processar imagens com SDKs do OSS, certifique-se de que o bucket de destino esteja associado a um projeto IMM.

Código de exemplo

Java

É necessário o OSS SDK for Java 3.17.4 ou posterior.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GetObjectRequest;
import java.io.File;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // Specify the endpoint of the region. In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the region of the endpoint. Example: cn-hangzhou. 
        String region = "cn-hangzhou";
        // 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 source image. Do not include the bucket name in the full path. 
        String objectName = "example.jpg";
        // Specify the full path of the processed image. Example: D:\\dest.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
        String pathName = "D:\\dest.jpg";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Crop an area of 200 × 200 pixels from the center of the maximum face in the image. 
            String image = "image/crop,g_face,w_200,h_200";
            GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
            request.setProcess(image);
            // Save the processed image to your local computer. 
            // If you specify only the name of the processed image such as dest.jpg without specifying the local path, the processed image is saved to the local path of the project to which the sample program belongs. 
            ossClient.getObject(request, new File("D:\\dest.jpg"));
        } 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

É necessário o OSS SDK for PHP 2.7.0 ou posterior.

<?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 the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
$provider = new 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 name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";
// Specify the full path of the source image. Do not include the bucket name in the full path. 
$object = "src.jpg";
// Specify the full path of the processed image. Example: D:\\dest.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
// If you specify only the name of the processed image such as dest.jpg without specifying the local path, the processed image is saved to the local path of the project to which the sample program belongs. 
$download_file = "D:\\dest.jpg";

$config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,        
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        // Specify the ID of the Alibaba Cloud region in which the bucket is located. 
        "region" => "cn-hangzhou"
    );
$ossClient = new OssClient($config);

// Crop an area of 200 × 200 pixels from the center of the maximum face in the image. 
$image = "image/crop,g_face,w_200,h_200";

$options = array(
    OssClient::OSS_FILE_DOWNLOAD => $download_file,
    OssClient::OSS_PROCESS => $image);

// Save the processed image to your local computer. 
$ossClient->getObject($bucket, $object, $options);                           

Python

É necessário o OSS SDK for Python 2.18.4 ou posterior.

# -*- coding: utf-8 -*-
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 Alibaba Cloud region in which the bucket is located. 
region = 'cn-hangzhou'
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)

# If the source image is stored in the root directory of the bucket, you can specify only the image name. Example: source-example.jpg. If the source image is not stored in the root directory of the bucket, you must specify the full path of the source image. Example: exampledir/source-example.jpg. 
key = 'source-example.jpg'

# Specify the full path of the processed image. Example: D:\\target-example.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
local_file_name = 'D:\\target-example.jpg'

# Crop an area of 200 × 200 pixels from the center of the maximum face in the image.
process = 'image/crop,g_face,w_200,h_200'

# Use the get_object method and pass the processing instruction by using the process parameter. 
result = bucket.get_object_to_file(key, local_file_name, process=process)

Go

É necessário o OSS SDK for Go 3.0.2 ou posterior.

package main

import (
	"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. 
	client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region("cn-hangzhou"))
	if err != nil {
		HandleError(err)
	}

	// Specify the name of the bucket in which the source image is stored. Example: examplebucket. 
	bucketName := "examplebucket"
	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 source image. Example: exampledir/example.jpg. 
	sourceImageName := "example.jpg"
	// Specify the name of the processed image. 
	targetImageName := "D://dest.jpg"
	// Crop an area of 200 × 200 pixels from the center of the maximum face in the image. 
	image := "image/crop,g_face,w_200,h_200"
	err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(image))
	if err != nil {
		HandleError(err)
	}
}

Resultado

O exemplo a seguir demonstra o efeito do recorte de uma área de 200 × 200 pixels centralizada no maior rosto detectado na imagem usando image/crop,g_face,w_200,h_200:

Imagem original

Imagem processada

source image

image

Recortar uma área centralizada no maior rosto detectado na imagem e ampliá-la por um fator de dois

Defina uma área de recorte ao redor do maior rosto detectado na imagem e, em seguida, amplie essa área por um fator de dois antes do recorte final:

  • Especifique a ação: crop.

  • Recorte uma área centralizada no maior rosto detectado na imagem: g_face.

  • Amplie a área recortada para o dobro do tamanho do maior rosto detectado: p_200.

Antes de processar imagens com SDKs do OSS, certifique-se de que o bucket de destino esteja associado a um projeto IMM.

Código de exemplo

Java

É necessário o OSS SDK for Java 3.17.4 ou posterior.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GetObjectRequest;
import java.io.File;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // Specify the endpoint of the region. In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the region of the endpoint. Example: cn-hangzhou. 
        String region = "cn-hangzhou";
        // 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 source image. Do not include the bucket name in the full path. 
        String objectName = "example.jpg";
        // Specify the full path of the processed image. Example: D:\\dest.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
        String pathName = "D:\\dest.jpg";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Crop an area of 200 × 200 pixels from the center of the maximum face in the image. 
            String image = "image/crop,g_face,w_200,h_200";
            GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
            request.setProcess(image);
            // Save the processed image to your local computer. 
            // If you specify only the name of the processed image such as dest.jpg without specifying the local path, the processed image is saved to the local path of the project to which the sample program belongs. 
            ossClient.getObject(request, new File("D:\\dest.jpg"));
        } 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

É necessário o OSS SDK for PHP 2.7.0 ou posterior.

<?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 the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
$provider = new 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 name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";
// Specify the full path of the source image. Do not include the bucket name in the full path. 
$object = "src.jpg";
// Specify the full path of the processed image. Example: D:\\dest.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
// If you specify only the name of the processed image such as dest.jpg without specifying the local path, the processed image is saved to the local path of the project to which the sample program belongs. 
$download_file = "D:\\dest.jpg";

$config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,        
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        // Specify the ID of the Alibaba Cloud region in which the bucket is located. 
        "region" => "cn-hangzhou"
    );
$ossClient = new OssClient($config);

// Crop an area of 200 × 200 pixels from the center of the maximum face in the image. 
$image = "image/crop,g_face,w_200,h_200";

$options = array(
    OssClient::OSS_FILE_DOWNLOAD => $download_file,
    OssClient::OSS_PROCESS => $image);

// Save the processed image to your local computer. 
$ossClient->getObject($bucket, $object, $options);                           

Python

É necessário o OSS SDK for Python 2.18.4 ou posterior.

# -*- coding: utf-8 -*-
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 Alibaba Cloud region in which the bucket is located. 
region = 'cn-hangzhou'
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)

# If the source image is stored in the root directory of the bucket, you can specify only the image name. Example: source-example.jpg. If the source image is not stored in the root directory of the bucket, you must specify the full path of the source image. Example: exampledir/source-example.jpg. 
key = 'source-example.jpg'

# Specify the full path of the processed image. Example: D:\\target-example.jpg. If an image that has the same name already exists in the path, the processed image overwrites the image. Otherwise, the processed image is saved in the path. 
local_file_name = 'D:\\target-example.jpg'

# Crop an area of 200 × 200 pixels from the center of the maximum face in the image.
process = 'image/crop,g_face,w_200,h_200'

# Use the get_object method and pass the processing instruction by using the process parameter. 
result = bucket.get_object_to_file(key, local_file_name, process=process)

Go

É necessário o OSS SDK for Go 3.0.2 ou posterior.

package main

import (
	"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. 
	client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region("cn-hangzhou"))
	if err != nil {
		HandleError(err)
	}

	// Specify the name of the bucket in which the source image is stored. Example: examplebucket. 
	bucketName := "examplebucket"
	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 source image. Example: exampledir/example.jpg. 
	sourceImageName := "example.jpg"
	// Specify the name of the processed image. 
	targetImageName := "D://dest.jpg"
	// Crop an area of 200 × 200 pixels from the center of the maximum face in the image. 
	image := "image/crop,g_face,w_200,h_200"
	err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(image))
	if err != nil {
		HandleError(err)
	}
}

Resultado

O exemplo a seguir demonstra o efeito do recorte de uma área centralizada no maior rosto detectado na imagem e sua ampliação por um fator de dois usando o parâmetro image/crop,g_face,p_200:

Imagem original

Imagem processada

source image

image