Les paramètres de découpage indexé permettent de découper une image source stockée dans Object Storage Service (OSS) selon une taille spécifique et de récupérer l'image souhaitée. Cette rubrique décrit les paramètres de découpage indexé et fournit des exemples.
Paramètres
Action : indexcrop
Le tableau suivant présente les paramètres configurables pour le découpage d'une image.
|
Paramètre |
Description |
Valeur valide |
|
x |
Largeur de chaque partition lors du découpage horizontal. Vous ne pouvez spécifier qu'un seul des paramètres x ou y. |
[1, largeur de l'image] |
|
y |
Hauteur de chaque partition lors du découpage vertical. Vous ne pouvez spécifier qu'un seul des paramètres x ou y. |
[1, hauteur de l'image] |
|
i |
Partition à sélectionner après le découpage. |
[0, nombre maximal de partitions) La valeur par défaut est 0 (première partition). Pour renvoyer la dernière partition, effectuez un découpage indexé en fonction de la taille de l'image et de la plage de valeurs du paramètre. |
Remarques sur l'utilisation
Si l'index spécifié dépasse le nombre de partitions, le système renvoie l'image source.
Si les paramètres x et y sont tous deux spécifiés avec des valeurs valides, la valeur de y est prise en compte.
Méthodes
Découper une image en lecture publique ou en lecture-écriture publique
Cette section illustre le découpage d'une image nommée example.jpg dans le bucket oss-console-img-demo-cn-hangzhou de la région Chine (Hangzhou). L'image est hébergée à l'URL suivante :
https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg
-
Découper l'image selon l'axe horizontal
Configurez les paramètres suivants pour découper l'image :
Découpez l'image par tranches de 100 pixels selon l'axe horizontal :
indexcrop,x_100Récupérez la première partition :
i_0
L'URL de traitement de l'image est la suivante : https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/indexcrop,x_100,i_0
. -
Découper l'image selon l'axe vertical
Configurez les paramètres suivants pour découper l'image :
Découpez l'image par tranches de 100 pixels selon l'axe vertical :
indexcrop,y_100Sélectionnez la 11e partition :
i_10
L'URL de traitement de l'image est la suivante : https://oss-console-img-demo-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/indexcrop,y_100,i_10.
Le système renvoie l'image source, car le nombre de partitions après découpage est inférieur à 10.

Découper une image privée
Utilisez les SDK OSS ou l'API OSS pour découper une image privée.
Utiliser les SDK OSS
L'exemple de code suivant montre comment découper une image privée à l'aide du SDK OSS pour les langages de programmation courants. Pour plus d'informations sur le découpage d'une image privée avec d'autres langages, consultez Présentation.
Java
Le SDK OSS pour Java version 3.17.4 ou ultérieure est requis.
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 in which the private image is stored. 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 object. 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.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Slice the image by 100 pixels along the horizontal axis and select the first partition.
String image = "image/indexcrop,x_100,i_0";
GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
request.setProcess(image);
// Set the name of the processed image to dest.jpg and save it 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
Le SDK OSS pour PHP version 2.7.0 ou ultérieure est requis.
<?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 object. Do not include the bucket name in the full path.
$object = "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.
// 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);
// Slice the image by 100 pixels along the horizontal axis and select the first partition.
$image = "image/indexcrop,x_100,i_0";
$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
Le SDK OSS pour Python version 2.18.4 ou ultérieure est requis.
# -*- 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.
# 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)
# Specify the name of the source image. If the image is not stored in the root directory of the bucket, you must include the full path of the image. Example: exampledir/src.gif.
key = 'example.jpg'
# Specify the name of the processed image.
new_pic = 'D:\\dest.jpg'
// Slice the image by 100 pixels along the horizontal axis and select the first partition.
image = 'image/indexcrop,x_100,i_0'
bucket.get_object_to_file(key, new_pic, process=image)
Go
Le SDK OSS pour Go version 3.0.2 ou ultérieure est requis.
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 image is not stored in the root directory of the bucket, you must include the full path of the image. Example: exampledir/src.gif.
sourceImageName := "example.jpg"
// Specify the name of the processed image.
targetImageName := "D://dest.jpg"
// Slice the image by 100 pixels along the horizontal axis and select the first partition.
image := "image/indexcrop,x_100,i_0"
err = bucket.GetObjectToFile(sourceImageName, targetImageName, oss.Process(image))
if err != nil {
HandleError(err)
}
}
Utiliser l'API RESTful
Si votre activité nécessite un niveau élevé de personnalisation, vous pouvez appeler directement les API RESTful. Pour ce faire, vous devez inclure le calcul de signature dans votre code. Pour plus d'informations, consultez (Recommandé) Inclure une signature V4.
Spécifiez les paramètres de découpage indexé lors de l'appel de l'opération GetObject pour découper une image.
GET /oss.jpg?x-oss-process=image/indexcrop,x_100,i_0 HTTP/1.1
Host: oss-example.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: OSS4-HMAC-SHA256 Credential=LTAI********************/20250417/cn-hangzhou/oss/aliyun_v4_request,Signature=a7c3554c729d71929e0b84489addee6b2e8d5cb48595adfc51868c299c0c218e