All Products
Search
Document Center

Object Storage Service:Custom crop

Last Updated:Sep 20, 2024

If you want to resize images stored in Object Storage Service (OSS) to fit your web page or meet layout requirements, you can use the custom crop feature to crop the images into the exact size that you need.

Scenarios

  • Web page design and production: When you design the layout of a web page, you may need to crop images to a specific size to fit web page elements, such as avatars, background images, and product displays.

  • Custom image size required by social media: Different social media platforms have different size requirements for images that you want to upload, such as thumbnails, images that you can post, and story images. You need to crop source images based on the recommended size to achieve optimal display performance.

  • Mobile app development: You must crop images such as icons, startup pages, and embedded pictures in an app based on specific specifications to ensure that the images are displayed as expected on devices with different resolutions and screen sizes.

  • Image database management: To meet the sorting and archiving requirements of institutions that have a large number of image resources, such as libraries and archives, you may need to crop images to a preset size.

Usage notes

  • If the specified starting X coordinate and Y coordinate exceed those of the source image, the BadRequest error code and the Advance cut's position is out of image. error message are returned.

  • If the width and height specified from the starting point exceed those of the source image, the source image is cropped to the boundaries.

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

Parameters

Action: crop.

The following table describes the parameters that you can configure to crop an image.

Parameter

Description

Valid value

w

The width that you want to crop.

[0, image width]

Default value: the maximum value.

h

The height 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 bound]

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 bound]

g

The position of the area that you want to crop in a 3 x 3 grid. The image is located in a 3 x 3 grid. The grid has nine tiles.

  • 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

For more information about how to calculate the position of each tile, see the following table.

The following table describes how to calculate the position of each tile in a 3 x 3 grid. srcW specifies the width of the source image and srcH specifies the height of the source image.

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

Methods

Crop public-read or public-read-write images

You can add image processing (IMG) parameters to the URL of a public-read or public-read write image to crop the image.

This section provides examples on how to crop an image named example1.jpg in the oss-console-img-demo-cn-hangzhou-3az bucket in the China (Hangzhou) region. The image is hosted at the following URL:.

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

Crop private images

In the following examples, a source image is cropped to an area of 900 × 900 pixels in the lower-right corner of the image.

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 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 an 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 an 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'

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

# Use the get_object method and pass the custom crop operation 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 path of the image. Example: example/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 an image. 
	image := "image/crop,w_900,h_900,g_se"
	err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(image))
	if err != nil {
		HandleError(err)
	}
}