All Products
Search
Document Center

Object Storage Service:Custom crop

Last Updated:May 29, 2025

You can use the custom crop feature to obtain images of a specific size.

Scenarios

  • Web design and development: When designing web layouts, you may need to crop images to specific dimensions to fit elements such as profile pictures, background images, and product display images.

  • Social media publishing: Different social media platforms have their own size requirements for uploaded images, such as cover photos, post images, and story images. You need to crop images according to the recommended dimensions to achieve the best display effect.

  • Mobile application development: Icons, splash screens, and embedded images in apps need to be cropped according to specifications to ensure proper display on devices with different resolutions and screen sizes.

  • Image database management: Organizations with large image resources, such as libraries and archives, may need to uniformly crop images to preset dimensions when organizing and archiving.

Notes

  • The specified width and height for custom cropping cannot exceed 16,384 pixels.

  • If the specified starting point coordinates are larger than the original image, a BadRequest error is returned: Advance cut's position is out of image..

  • If the specified crop width or height exceeds the boundary of the original image, the system automatically crops to the edge of the original image.

Operations

You can use object URLs, OSS SDKs, or API operations to configure IMG parameters that are used to process images. You can use object URLs to configure IMG parameters only for public-read or public-read-write images. If you want to configure IMG parameters for private images, use OSS SDKs or API operations. For more information, see IMG implementation modes.

Crop public-read or public-read-write images

If the access control list (ACL) of the image object that you want to process is public-read or public-read-write, you can add IMG parameters to the URL of the object to allow anonymous users to access the processed object.

The following table describes how to add the ?x-oss-process=image/crop,parame_value parameter to the URL of a public-read image. You need to replace parame_value with the specific parameters and values supported in Parameters based on your business requirements. Multiple parameters can be used together.

URL of the source image

URL used to process the source 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 Alibaba Cloud SDKs

The following sample code provides examples on how to crop a private image by using OSS SDKs for common programming languages. For examples on how to crop private images by using other SDKs, see SDK overview.

Java

OSS SDK for Java V3.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 {
        // 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 bucket. 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 paths.
        String objectName = "example.jpg";
        // Specify the full path of the processed image. Example: D:\\dest.jpg. If the specified local file exists, the object to download replaces the file. If the specified local file does not exist, the downloaded file is saved in the path.
        String pathName = "D:\\dest.jpg";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release resources.
        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 device.
            // If you specify only the name of the local file such as dest.jpg without specifying the local path of the file, 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 execute 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 paths.
$object = "src.jpg";
// Specify the full path of the processed image. Example: D:\\dest.jpg. If the specified local file exists, the object to download replaces the file. If the specified local file does not exist, the downloaded file is saved in the path.
// If you specify only the name of the local file such as dest.jpg without specifying the local path of the file, 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 device.
$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 execute 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 for 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 the specified local file exists, the object to download replaces the file. If the specified local file does not exist, the downloaded file is saved in the path.
local_file_name = 'D:\\target-example.jpg'

# 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 execute 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.
	// Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint 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 image is not stored in the root directory of the bucket, you must specify the full path of the 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 RESTful APIs

If your program requires more custom options, you can call RESTful API operations. To call a RESTful API operation, you must include the signature calculation in your code. For more information about how to calculate the signature for the Authorization header, see Signature version 4 (recommended).

You can add crop parameters to the GetObject operation to process images. 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, you must first bind the bucket to an IMM project. For information about how to bind a bucket to an IMM project, see Quick Start.

Use Alibaba Cloud SDKs

The following sample code provides examples on how to crop a private image by using OSS SDKs for common programming languages. For examples on how to crop private images by using other SDKs, see SDK overview.

Java

OSS SDK for Java V3.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 {
        // 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 bucket. Example: cn-hangzhou.
        String region = "cn-hangzhou";
        // Obtain access credentials from environment variables. Before you execute the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        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 paths.
        String objectName = "example.jpg";
        // Specify the full path of the processed image. Example: D:\\dest.jpg. If the specified local file exists, the object to download replaces the file. If the specified local file does not exist, the downloaded file 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 device.
            // If you specify only the name of the local file such as dest.jpg without specifying the local path of the file, 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 execute 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 paths.
$object = "src.jpg";
// Specify the full path of the processed image. Example: D:\\dest.jpg. If the specified local file exists, the object to download replaces the file. If the specified local file does not exist, the downloaded file is saved in the path.
// If you specify only the name of the local file such as dest.jpg without specifying the local path of the file, 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 device.
$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 execute 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 for 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 the specified local file exists, the object to download replaces the file. If the specified local file does not exist, the downloaded file 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 execute 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.
	// Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint 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 image is not stored in the root directory of the bucket, you must specify the full path of the 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)
	}
}

Use RESTful APIs

If your program requires more custom options, you can call RESTful API operations. To call a RESTful API operation, you must include the signature calculation in your code. For more information about how to calculate the signature for the Authorization header, see Signature version 4 (recommended).

You can add crop parameters to the GetObject operation 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

Operation name: crop

Configure the following parameters:

Parameter

Description

Valid values

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 cropped area. The default value is the X coordinate of the upper-left corner of the image.

[0, image width]

y

The Y coordinate of the cropped area. The default value is the Y coordinate of the upper-left corner of the image.

[0, image height]

g

The position of the area that you want to crop in a 3 by 3 grid. The origin can be set to one of nine 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: maximum face

  • auto

Note

The following information applies to the face and auto parameters:

  • You must bind the bucket to an IMM project. For information about how to bind a bucket to an IMM project by using the OSS console or by calling API operations, see Quick Start and AttachOSSBucket - Bind a bucket.

  • Anonymous access is not supported.

  • You must have the permissions that are required to use IMM features in OSS. For more information, see Permissions.

  • The auto parameter ignores the w, h, and p parameters that you specify. The algorithm recommends values for w and h.

For information about how to calculate the position of each crop origin, see Calculation method.

p

The parameter at which the blurred area is resized.

[1,200], in percentage.

Note

This parameter takes effect only when g_face is set.

The following table describes the calculation method for each crop origin position. In the table, srcW indicates the width of the source image, and srcH indicates the height of the source image.

Crop origin

Position 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

Sample code

Crop an image from a specific starting point

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

  • Crop operation: crop

  • Starting point (800,500): x_800,y_500

  • Crop to the boundaries: By default, the maximum values of w and h are used to crop the image. You do not need to specify the w and h parameters.

For public-read-write images, you can add ?x-oss-process=image/crop,x_800,y_500 to the end of the image URL. OSS processes the image in real time based on the specified parameters and returns the processed result. If you want to crop your private images, see Crop private images.

Sample effect

The following example shows how to add the ?x-oss-process=image/crop,x_800,y_500 parameter to the URL of the source image to crop the image from the starting point (800, 500) to the boundaries:

Source image

Processed image

image

image

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

Image processing URL: 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)

  • Crop operation: crop

  • Starting point (800,500): x_800,y_500

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

For public-read-write images, you can add ?x-oss-process=image/crop,x_800,y_500,w_300,h_300 to the end of the image URL. OSS processes the image in real time based on the specified parameters and returns the processed result. If you want to crop your private images, see Crop private images.

Sample effect

The following example shows how to add the ?x-oss-process=image/crop,x_800,y_500,w_300,h_300 parameter to the URL of the source image to crop an area of 300 × 300 pixels from the starting point (800, 500):

Source image

Processed image

image

image

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

Image processing URL: 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

  • Crop operation: crop

  • Starting point in the lower-right corner of the source image: g_se

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

For public-read-write images, you can add ?x-oss-process=image/crop,g_se,w_900,h_900 to the end of the image URL. OSS processes the image in real time based on the specified parameters and returns the processed result. If you want to crop your private images, see Crop private images.

Sample effect

The following example shows how to add the ?x-oss-process=image/crop,g_se,w_900,h_900 parameter to the URL of the source image to crop an area of 900 × 900 pixels in the lower-right corner of the image:

Source image

Processed image

image

image

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

Image processing URL: 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)

  • Crop operation: crop

  • Starting point in the lower-right corner of the source image with an offset of (100,200): g_se,x_100,y_200

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

For public-read-write images, you can add ?x-oss-process=image/crop,g_se,x_100,y_200,w_900,h_900 to the end of the image URL. OSS processes the image in real time based on the specified parameters and returns the processed result. If you want to crop your private images, see Crop private images.

Sample effect

The following example shows how to add the ?x-oss-process=image/crop,g_se,x_100,y_200,w_900,h_900 parameter to the URL of the source image to crop an area of 900 × 900 pixels in the lower-right corner of the image:

Source image

Processed image

image

image

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

Image processing URL: 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:

  • Crop operation: crop

  • Smart algorithm cropping: g_auto

To use OSS SDKs to process images, you must bind the bucket to an IMM project. The following sample code provides an example:

Sample code

Java

OSS SDK for Java V3.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 {
        // 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 bucket. Example: cn-hangzhou.
        String region = "cn-hangzhou";
        // Obtain a credential from the 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 paths.
        String objectName = "example.jpg";
        // Specify the full path of the processed image. Example: D:\\dest.jpg. If the specified local file exists, the object to download replaces the file. Otherwise, a file is created.
        String pathName = "D:\\dest.jpg";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release resources.
        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 device.
            // 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 for 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 paths.
$object = "src.jpg";
// Specify the full path of the processed image. Example: D:\\dest.jpg. If the specified local file exists, the object to download replaces the file. Otherwise, a file is created.
// If you specify only the name of the local file such as dest.jpg without specifying the local path of the file, 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 device.
$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 for 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 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 to which you want to save the processed image. Example: D:\\target-example.jpg. If the specified local file exists, the downloaded object overwrites the file. Otherwise, a file is created.
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.
	// Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint 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 image is not stored in the root directory of the bucket, you must specify the full path of the 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 shows how to use the image/crop,g_auto parameter to crop an image by using a smart algorithm:

Original image

Processed image

原图

image

Crop an area based on the specified width and height from the center of the maximum face in an image

The processing parameters to crop an area of 200 px × 200 px from the center of the maximum face are as follows:

  • Blur processing: crop

  • Crop with the maximum face as the center: g_face

  • Crop area of 200 px × 200 px: w_200,h_200

To use OSS SDKs to process images, you must bind the bucket to an IMM project. The following sample code provides an example:

Sample code

Java

OSS SDK for Java V3.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 {
        // 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 bucket. 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 paths.
        String objectName = "example.jpg";
        // Specify the full path of the processed image. Example: D:\\dest.jpg. If the specified local file exists, the object to download replaces the file. Otherwise, a file is created.
        String pathName = "D:\\dest.jpg";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release resources.
        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 device.
            // 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 V2.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 paths.
$object = "src.jpg";
// Specify the full path of the processed image. Example: D:\\dest.jpg. If the specified local file exists, the object to download replaces the file. Otherwise, a file is created.
// If you specify only the name of the local file such as dest.jpg without specifying the local path of the file, 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 device.
$ossClient->getObject($bucket, $object, $options);                           

Python

OSS SDK for Python V2.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 for 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 the specified local file exists, the object to download replaces the file. Otherwise, a file is created.
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 V3.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.
	// Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint 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 image to process. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg.
	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 images show the effect of using the image/crop,g_face,w_200,h_200 parameter to crop an area of 200 px × 200 px from the center of the maximum face in the image:

Original image

Processed image

原图

image

Crop an area from the center of the maximum face and enlarge it to twice the size

This processing method first determines a cropping area around the position of the maximum face, and then enlarges this area by 2 times before cropping. Configure the following parameters:

  • Blur processing: crop

  • Crop with the maximum face as the center: g_face

  • Crop range with 2× magnification: p_200

To use OSS SDKs to process images, you must bind the bucket to an IMM project. The following sample code provides an example:

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 {
        // 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 bucket. 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 paths.
        String objectName = "example.jpg";
        // Specify the full path of the processed image. Example: D:\\dest.jpg. If the specified local file exists, the object to download replaces the file. Otherwise, a file is created.
        String pathName = "D:\\dest.jpg";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release resources.
        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 device.
            // 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 paths.
$object = "src.jpg";
// Specify the full path of the processed image. Example: D:\\dest.jpg. If the specified local file exists, the object to download replaces the file. Otherwise, a file is created.
// If you specify only the name of the local file such as dest.jpg without specifying the local path of the file, 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 device.
$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 for 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 the specified local file exists, the object to download replaces the file. Otherwise, a file is created.
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.
	// Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint 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 image to process. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg.
	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 shows how to use the image/crop,g_face,p_200 parameter to determine a cropping area around the position of the maximum face in an image, and then enlarge this area by 2 times before cropping:

Original image

Processed image

原图

image