Custom crop

更新时间:
复制 MD 格式

Crop images to exact dimensions by specifying the width, height, starting coordinates, and anchor position.

Scenarios

  • Web design: Crop images to fit layout elements such as avatars, backgrounds, and product galleries.

  • Social media image specifications: Different social media platforms impose specific size requirements for various types of images, including thumbnails, images that you can post, and story images. To ensure optimal visual presentation, images are required to be cropped to the recommended dimensions in advance.

  • Mobile app development: Crop app icons, splash screens, and in-app graphics to match various device resolutions.

  • Image database management: In organizations such as libraries and archives that maintain extensive image repositories, it is necessary to standardize image dimensions by cropping to predefined sizes during cataloging and archival workflows.

Usage notes

  • The specified width and height of the processed image must not exceed 16,384 pixels.

  • If the starting coordinates exceed the source image boundaries, a BadRequest error is returned: Advance cut's position is out of image.

  • If the specified width and height exceed the source image dimensions, the crop area is constrained to the image boundaries.

Methods

You can use object URLs, OSS SDKs or call API operations to configure image processing (IMG) parameters. Object URLs are only supported for publicly accessible images (public-read or public-read-write). For private images, use OSS SDKs or directly call API operations. For more information, see Image processing methods .

Crop public-read or public-read-write images

If the image ACL is public-read or public-read-write, append IMG parameters to the object URL to access the processed image.

In this example, ?x-oss-process=image/crop,parame_value is appended to the URL of a public-read image. You only need to replace parame_value with the specific parameters and values described in the Parameters section. You can include multiple parameters in the URL when applicable.

URL of the source image

URL used to access the processed image

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

Crop private images

Use OSS SDKs

Sample code for cropping a private image with OSS SDKs. For other programming languages, see Overview .

Java

OSS SDK for Java 3.17.4 or later is required.

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

OSS SDK for PHP 2.7.0 or later is required.

<?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

OSS SDK for Python 2.18.4 or later is required.

# -*- 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

OSS SDK for Go 3.0.2 or later is required.

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)
	}
}

Use the OSS API

You can directly initiate RESTful API requests. Include the signature calculation in your code. For how to calculate the Authorization header, see (Recommended) Include a V4 signature.

You can specify crop parameters in the GetObject operation to crop the images into the exact size that you need. For more information, see 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

Private images (IMM binding required)

To use the g_auto or g_face parameter, first bind an IMM project to the bucket as described in Quick Start.

Use OSS SDKs

Sample code for cropping private images with common OSS SDKs. Other languages are covered in the SDK Overview.

Java

OSS SDK for Java 3.17.4 or later is required.

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 {
        // Endpoint uses East China 1 (Hangzhou) as an example. Fill in the actual endpoint for other regions.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Fill in the region information corresponding to the endpoint, for example cn-hangzhou.
        String region = "cn-hangzhou";
        // Obtain access credentials from environment variables. Before running this code example, make sure you have set the environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Fill in the bucket name, for example examplebucket.
        String bucketName = "examplebucket";
        // Fill in the complete path of the source image. The object complete path cannot contain the bucket name.
        String objectName = "example.jpg";
        // Fill in the complete path of the local file to save the custom cropped image, for example D:\\dest.jpg. If the specified local file exists it will be overwritten, if it does not exist a new one will be created.
        String pathName = "D:\\dest.jpg";

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

        try {
            // Crop with face as center to200 px*200 px。
            String image = "image/crop,g_face,w_200,h_200";
            GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
            request.setProcess(image);
            // Save the processed image to local。
            // If no local path is specified and only the file name is filled in (for example dest.jpg), the file will be saved by default to the local path corresponding to the example program project.
            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

OSS SDK for PHP 2.7.0 or later is required.

<?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;

// Get access credentials from environment variables. Before running this code example, make sure you have set the environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
$provider = new EnvironmentVariableCredentialsProvider();
// Fill in yourEndpoint with the Endpoint corresponding to the region where the Bucket is located. For example, if the Bucket is in East China 1 (Hangzhou), fill in the Endpoint as https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Fill in the Bucket name, for example examplebucket.
$bucket= "examplebucket";
// Fill in the complete path of the source image. The Object complete path cannot contain the Bucket name.
$object = "src.jpg";
// Fill in the complete path for saving the custom cropped file locally, for example D:\\dest.jpg. If the specified local file exists it will be overwritten, if it doesn't exist it will be created.
// If no local path is specified and only the local file name is filled in (for example dest.jpg), the file will be saved by default to the local path corresponding to the project where the example program belongs.
$download_file = "D:\\dest.jpg";

$config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,        
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        // Fill in Alibaba Cloud generalRegion ID。
        "region" => "cn-hangzhou"
    );
$ossClient = new OssClient($config);

// Crop with face as center to a range of200 px*200 px。
$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 locally。
$ossClient->getObject($bucket, $object, $options);                           

Python

OSS SDK for Python 2.18.4 or later is required.

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Get access credentials from environment variables. Before running this code example, make sure you have set the environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Fill in the Endpoint corresponding to the region where the Bucket is located. Taking East China 1 (Hangzhou) as an example, the Endpoint is https://oss-cn-hangzhou.aliyuncs.com.
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
# Fill in Alibaba Cloud generalRegion ID。
region = 'cn-hangzhou'
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)

# If the source image is located in the Bucket root directory, directly fill in the image name source-example.jpg. If the original image is not in the Bucket root directory, you need to include the complete path of the original image, for example exampledir/source-example.jpg.
key = 'source-example.jpg'

# Fill in the complete path of the local file, for example D:\target-example.jpg. If the specified local file exists it will be overwritten, if it does not exist a new one will be created.
local_file_name = 'D:\target-example.jpg'

# Build custom crop processing parameters. Crop range centered on face is 200 px*200 px
process = 'image/crop,g_face,w_200,h_200'

# Use the get_object method and pass in the processing instructions through the process parameter.
result = bucket.get_object_to_file(key, local_file_name, process=process)

Go

OSS SDK for Go 3.0.2 or later is required.

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() {
	// Get access credentials from environment variables. Before running this code example, make sure you have set the environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}

	// Create OSS client instance.
	// Fill in yourEndpoint with the Endpoint corresponding to the Bucket. Taking East China 1 (Hangzhou) as an example, fill in https://oss-cn-hangzhou.aliyuncs.com. For other regions, please fill in according to the actual situation.
	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 Bucket name, for example examplebucket.
	bucketName := "examplebucket"
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		HandleError(err)
	}

	// Specify the source image name. If the image is not in the Bucket root directory, you need to include the complete path of the image, for example exampledir/example.jpg.
	sourceImageName := "example.jpg"
	// Specify the processed image name.
	targetImageName := "D://dest.jpg"
	// Crop range centered on face to200 px*200 px
	image := "image/crop,g_face,w_200,h_200"
	err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(image))
	if err != nil {
		HandleError(err)
	}
}

Use the REST API

You can directly initiate REST API requests. This requires manually calculating signatures as described in Signature Version 4 (Recommended).

Use the GetObject operation to add crop parameters to process images. For more information, see GetObject.

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

Parameters

Action: crop

The following table describes the parameters for image cropping.

Parameter

Description

Valid value

w

The width of the area that you want to crop.

[0, image width]

Default value: the maximum value.

h

The height of the area that you want to crop.

[0, image height]

Default value: the maximum value.

x

The X coordinate of the area that you want to crop. The default value is the X coordinate of the upper-left corner of the image.

[0, image width]

y

The Y coordinate of the area that you want to crop. The default value is the Y coordinate of the upper-left corner of the image.

[0, image height]

g

The anchor position within a 3×3 grid. The image is divided into nine tiles, and the crop area is aligned to one of these positions.

  • nw: upper left

  • north: upper middle

  • ne: upper right

  • west: middle left

  • center: center

  • east: middle right

  • sw: lower left

  • south: lower middle

  • se: lower right

  • face: largest face

  • auto: automatic

Note

Notes on the face and auto parameters:

  • You must bind an IMM project. Bind via the console (Quick Start) or API (AttachOSSBucket).

  • Anonymous access is not supported.

  • You must have the required IMM processing permissions. Permissions.

  • The auto parameter ignores the input w, h, and p parameters and uses algorithm-recommended w and h values.

For how to calculate the position of each tile, see the table below.

p

Scaling parameter.

[1,200], as a percentage.

Note

This parameter takes effect only when g_face is set.

The following table shows how tile positions are calculated. srcW is the source image width and srcH is the source image height.

Tile

Calculation method

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

Examples

Crop from a specific starting point

Crop an image from the starting point (800, 50) to the boundaries:

  • Specify the action: crop.

  • Specify the starting point (800, 500): x_800,y_500.

  • Crop to the boundaries: The maximum of the w and h values is used by default for cropping. Therefore, specifying the w and h parameters is optional.

To crop a public-read or public-read-write image, append ?x-oss-process=image/crop,x_800,y_500 to the image URL. OSS dynamically applies the cropping operation upon request and returns the processed image. For how to crop a private image, see Crop private images .

Demo

The following example describes how to crop a source image from the starting point (800, 50) to the boundaries by appending ?x-oss-process=image/crop,x_800,y_500 to the URL of the source image:

Source image

Processed image

image

image

URL of the source image: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg

URL used to access the processed image: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg?x-oss-process=image/crop,x_800,y_500

Crop an area based on the specified width and height from a specific starting point

Crop an area of 300 × 300 pixels from the starting point (800, 500):

  • Specify the action: crop.

  • Specify the starting point (800, 500): x_800,y_500.

  • Crop an area of 300 × 300 pixels: w_300,h_300.

To crop a public-read or public-read-write image, append ?x-oss-process=image/crop,x_800,y_500,w_300,h_300 to the image URL. OSS dynamically applies the cropping operation upon request and returns the processed image. For how to crop a private image, see Crop private images.

Sample effect

The following table demonstrates the effect of extracting a 300 × 300 pixel area from the specified starting point (800, 500) by appending ?x-oss-process=image/crop,x_800,y_500,w_300,h_300 to the URL of the source image:

Source image

Processed image

image

image

URL of the source image: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg

URL used to access the processed image: 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

Crop an area based on the specified width and height in the lower-right corner of an image

Crop an area of 900 × 900 pixels in the lower-right corner of an image

  • Specify the action: crop.

  • Specify the starting point in the lower-right corner: g_se.

  • Crop an area of 900 × 900 pixels: w_900,h_900.

To crop a public-read or public-read-write image, append ?x-oss-process=image/crop,g_se,w_900,h_900 to the image URL. OSS dynamically applies the cropping operation upon request and returns the processed image. For how to crop a private image, see Crop private images.

Sample effect

The following table demonstrates the effect of cropping a 900 × 900 pixel area from the lower-right corner of an image by appending ?x-oss-process=image/crop,g_se,w_900,h_900 to the URL of the source image:

Source image

Processed image

image

image

URL of the source image: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg

URL used to access the processed image: 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

Crop an area based on the specified width and height in the lower-right corner of an image and stretch the cropped area

Crop an area of 900 × 900 pixels in the lower-right corner of an image and stretch the cropped area downward by (100,200):

  • Specify the action: crop.

  • Specify the starting point in the lower-right corner of the image and stretch the cropped area downward by (100,200): g_se,x_100,y_200

  • Crop an area of 900 × 900 pixels: w_900,h_900.

To crop a public-read or public-read-write image, append ?x-oss-process=image/crop,g_se,x_100,y_200,w_900,h_900 to the image URL. OSS dynamically applies the cropping operation upon request and returns the processed image. For how to crop a private image, see Crop private images.

Sample effect

The following table demonstrates the effect of cropping a 900 × 900 pixel area in the lower-right corner of an image by appending ?x-oss-process=image/crop,g_se,x_100,y_200,w_900,h_900 to the URL of the source image:

Source image

Processed image

image

image

URL of the source image: https://oss-console-img-demo-cn-hangzhou-3az.oss-cn-hangzhou.aliyuncs.com/example1.jpg

URL used to access the processed image: 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

Crop an image by using smart cropping

Configure the following parameters to crop an image by using smart cropping:

  • Specify the action: crop.

  • Specify the algorithm: g_auto

Before processing images with OSS SDKs, ensure that the target bucket is associated with an Intelligent Media Management (IMM) project.

Sample code

Java

OSS SDK for Java 3.17.4 or later is required.

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

OSS SDK for PHP 2.7.0 or later is required.

<?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

OSS SDK for Python 2.18.4 or later is required.

# -*- 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

OSS SDK for Go 3.0.2 or later is required.

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)
	}
}

Sample effect

The following table demonstrates the effect of applying the image/crop,g_auto parameter and intelligent algorithms to crop the image:

Source image

Processed image

source image

image

Perform a fixed-dimension crop centered on the largest detected face in the image

Crop a 200 × 200 pixel area centered on the largest detected face in the image:

  • Specify the action: crop.

  • Crop an area centered on the largest detected face in the image: g_face.

  • Crop a 200 × 200 pixel area: w_200,h_200.

Before processing images with OSS SDKs, ensure that the target bucket is associated with an IMM project.

Sample code

Java

OSS SDK for Java 3.17.4 or later is required.

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

OSS SDK for PHP 2.7.0 or later is required.

<?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

OSS SDK for Python 2.18.4 or later is required.

# -*- 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

OSS SDK for Go 3.0.2 or later is required.

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)
	}
}

Sample effect

The following example demonstrates the effect of cropping an area of 200 × 200 pixels centered on the largest detected face in the image by using image/crop,g_face,w_200,h_200:

Source image

Processed image

source image

image

Crop an area centered on the largest detected face in the image and scale it up by a factor of two

Define a cropping area around the largest detected face in the image, then scale this area by a factor of two before the final crop:

  • Specify the action: crop.

  • Crop an area centered on the largest detected face in the image: g_face.

  • Scale the cropped area to twice the size of the largest detected face: p_200.

Before processing images with OSS SDKs, ensure that the target bucket is associated with an IMM project.

Sample code

Java

OSS SDK for Java 3.17.4 or later is required.

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

OSS SDK for PHP 2.7.0 or later is required.

<?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

OSS SDK for Python 2.18.4 or later is required.

# -*- 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

OSS SDK for Go 3.0.2 or later is required.

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)
	}
}

Sample effect

The following example demonstrates the effect of cropping an area centered on the largest detected face in the image and scale it up by a factor of two by using the image/crop,g_face,p_200 parameter:

Source image

Processed image

source image

image