Le traitement d'images est un service évolutif, sécurisé, économique et hautement fiable proposé par OSS. Après avoir chargé une image dans OSS, vous pouvez la traiter sur n'importe quel appareil connecté à Internet via de simples interfaces RESTful.
Remarques
Si vous utilisez des outils d'empaquetage tels que Webpack et Browserify, installez le SDK OSS pour Browser.js en exécutant la commande npm install ali-oss.
Si vous souhaitez accéder à un compartiment OSS depuis un navigateur sans y avoir configuré de règles CORS, le navigateur rejettera la requête. Vous devez donc configurer des règles CORS pour tout compartiment auquel vous souhaitez accéder depuis un navigateur. Pour plus d'informations, consultez la rubrique Installation.
-
Le SDK OSS pour Browser.js s'exécute principalement dans les navigateurs. Pour éviter d'exposer votre paire AccessKey, nous vous recommandons d'utiliser des identifiants temporaires obtenus auprès du Security Token Service (STS) pour accéder à OSS.
Les identifiants temporaires se composent d'une paire AccessKey et d'un jeton de sécurité. La paire AccessKey comprend un AccessKey ID et un AccessKey Secret. Pour savoir comment obtenir des identifiants temporaires, consultez la rubrique Utilisation de STS pour l'autorisation d'accès temporaire.
Traitement d'images à l'aide de paramètres de traitement d'image
Traitement d'une image à l'aide d'un seul paramètre de traitement d'image
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<!--Import the SDK file.-->
<script
type="text/javascript"
src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
></script>
<script type="text/javascript">
const client = new OSS({
authorizationV4: true,
// Obtain a temporary AccessKey pair (AccessKey ID and AccessKey secret) from the STS service.
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// Obtain a security token (SecurityToken) from the STS service.
stsToken: 'yourSecurityToken',
refreshSTSToken: async () => {
// Obtain temporary access credentials from your STS service.
const info = await fetch("your_sts_server");
return {
accessKeyId: info.accessKeyId,
accessKeySecret: info.accessKeySecret,
stsToken: info.stsToken,
};
},
// The interval to refresh temporary access credentials. Unit: milliseconds.
refreshSTSTokenInterval: 300000,
// Specify the bucket name. For example, examplebucket.
bucket: "examplebucket",
// Replace yourRegion with the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: "yourRegion",
});
// Scale the image to a fixed width and height of 100 px.
async function scale() {
try {
// Specify the full path of the object. For example, exampledir/exampleobject.jpg. The full path cannot contain the bucket name.
const result = await client.signatureUrl("exampledir/exampleobject.jpg", {
expires: 3600,
process: "image/resize,m_fixed,w_100,h_100",
});
console.log(result);
} catch (e) {
console.log(e);
}
}
scale();
</script>
</body>
</html>
Traitement d'une image à l'aide de plusieurs paramètres de traitement d'image
Pour utiliser plusieurs paramètres de traitement d'image, séparez-les par une barre oblique (/).
!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<!--Import the SDK file.-->
<script
type="text/javascript"
src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
></script>
<script type="text/javascript">
const client = new OSS({
authorizationV4: true,
// Obtain a temporary AccessKey pair (AccessKey ID and AccessKey secret) from the STS service.
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// Obtain a security token (SecurityToken) from the STS service.
stsToken: 'yourSecurityToken',
refreshSTSToken: async () => {
// Obtain temporary access credentials from your STS service.
const info = await fetch("your_sts_server");
return {
accessKeyId: info.accessKeyId,
accessKeySecret: info.accessKeySecret,
stsToken: info.stsToken,
};
},
// The interval to refresh temporary access credentials. Unit: milliseconds.
refreshSTSTokenInterval: 300000,
// Specify the bucket name. For example, examplebucket.
bucket: "examplebucket",
// Replace yourRegion with the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: "oss-cn-hangzhou",
});
// Scale the image to a fixed width and height of 100 px, and then rotate it by 90 degrees.
async function resize() {
try {
// Specify the full path of the object. For example, exampledir/exampleobject.jpg. The full path cannot contain the bucket name.
const result = await client.signatureUrl("exampledir/exampleobject.jpg", {
expires: 3600,
process: "image/resize,m_fixed,w_100,h_100/rotate,90",
});
console.log(result);
} catch (e) {
console.log(e);
}
}
resize();
</script>
</body>
</html>
Traitement d'images à l'aide de styles d'image
-
Créez un style d'image.
Vous pouvez ajouter plusieurs paramètres de traitement d'image à un style pour effectuer des opérations complexes. Pour plus d'informations, consultez la rubrique Styles d'image.
-
Traitez une image à l'aide du style d'image.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> </head> <body> <!--Import the SDK file.--> <script type="text/javascript" src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js" ></script> <script type="text/javascript"> const client = new OSS({ authorizationV4: true, // Obtain a temporary AccessKey pair (AccessKey ID and AccessKey secret) from the STS service. accessKeyId: 'yourAccessKeyId', accessKeySecret: 'yourAccessKeySecret', // Obtain a security token (SecurityToken) from the STS service. stsToken: 'yourSecurityToken', refreshSTSToken: async () => { // Obtain temporary access credentials from your STS service. const info = await fetch("your_sts_server"); return { accessKeyId: info.accessKeyId, accessKeySecret: info.accessKeySecret, stsToken: info.stsToken, }; }, // The interval to refresh temporary access credentials. Unit: milliseconds. refreshSTSTokenInterval: 300000, // Specify the bucket name. For example, examplebucket. bucket: "examplebucket", // Replace yourRegion with the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou. region: "oss-cn-hangzhou", }); // Scale the image to a fixed width and height of 100 px, and then rotate it by 90 degrees. async function style() { try { // Specify the full path of the object. For example, exampledir/exampleobject.jpg. The full path cannot contain the bucket name. const result = await client.signatureUrl("exampledir/exampleobject.jpg", { expires: 3600, // Replace yourCustomStyleName with the name of the image style that you created in Step 1. process: "style/yourCustomStyleName", }); console.log(result); } catch (e) { console.log(e); } } style(); </script> </body> </html>
Persistance du traitement d'image
Par défaut, le service de traitement d'images ne sauvegarde pas les images traitées. Utilisez la fonctionnalité de persistance du traitement d'image pour enregistrer une image traitée dans le même compartiment que l'image source.
L'exemple de code suivant montre comment utiliser la persistance du traitement d'image.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<!--Import the SDK file.-->
<script
type="text/javascript"
src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
></script>
<script type="text/javascript">
const client = new OSS({
authorizationV4: true,
// Obtain a temporary AccessKey pair (AccessKey ID and AccessKey secret) from the STS service.
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// Obtain a security token (SecurityToken) from the STS service.
stsToken: 'yourSecurityToken',
refreshSTSToken: async () => {
// Obtain temporary access credentials from your STS service.
const info = await fetch("your_sts_server");
return {
accessKeyId: info.accessKeyId,
accessKeySecret: info.accessKeySecret,
stsToken: info.stsToken,
};
},
// The interval to refresh temporary access credentials. Unit: milliseconds.
refreshSTSTokenInterval: 300000,
// Specify the bucket name. For example, examplebucket.
bucket: "examplebucket",
// Replace yourRegion with the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: "oss-cn-hangzhou",
});
// Specify the full path of the source object. For example, exampledir/src.png. The full path cannot contain the bucket name.
const sourceImage = "exampledir/src.png";
// Specify the full path of the destination object for the processed image. For example, exampledir/dest.png. The full path cannot contain the bucket name.
const targetImage = "exampledir/dest.png";
async function processImage(processStr, targetBucket) {
const result = await client.processObjectSave(
sourceImage,
targetImage,
processStr,
targetBucket
);
console.log(result.res.status);
}
// Scale the source image to a fixed width and height of 100 px and save it to the source bucket.
processImage("image/resize,m_fixed,w_100,h_100", "examplebucket");
</script>
</body>
</html>
Génération d'une URL signée pour un fichier avec des paramètres de traitement d'image
L'accès à un fichier privé via son URL nécessite une signature. Vous ne pouvez pas ajouter directement des paramètres de traitement d'image à une URL signée. Pour traiter une image privée, vous devez inclure les paramètres de traitement d'image dans la signature. L'exemple de code suivant illustre cette procédure :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<!--Import the SDK file.-->
<script
type="text/javascript"
src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"
></script>
<script type="text/javascript">
const client = new OSS({
authorizationV4: true,
// Obtain a temporary AccessKey pair (AccessKey ID and AccessKey secret) from the STS service.
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// Obtain a security token (SecurityToken) from the STS service.
stsToken: 'yourSecurityToken',
refreshSTSToken: async () => {
// Obtain temporary access credentials from your STS service.
const info = await fetch("your_sts_server");
return {
accessKeyId: info.accessKeyId,
accessKeySecret: info.accessKeySecret,
stsToken: info.stsToken,
};
},
// The interval to refresh temporary access credentials. Unit: milliseconds.
refreshSTSTokenInterval: 300000,
// Specify the bucket name. For example, examplebucket.
bucket: "examplebucket",
// Replace yourRegion with the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: "oss-cn-hangzhou",
});
// Generate a signed URL for a file with image processing parameters and set the expiration time of the signed URL to 600s. The maximum expiration time is 32400s.
const signUrl = client.signatureUrl("oss.png", {
expires: 600,
process: "image/resize,w_300",
});
console.log("signUrl=" + signUrl);
</script>
</body>
</html>