O processamento de imagens é um serviço escalável, seguro, econômico e altamente confiável do OSS. Após carregar uma imagem no OSS, processe-a em qualquer dispositivo conectado à internet por meio de interfaces RESTful simples.
Observações de uso
Ao usar ferramentas de empacotamento como Webpack e Browserify, instale o OSS SDK for Browser.js executando o comando npm install ali-oss.
Se você tentar acessar um bucket do OSS pelo navegador sem regras de CORS configuradas, o navegador rejeitará a solicitação. Portanto, configure regras de CORS no bucket para permitir o acesso via navegador. Para mais informações, consulte Instalação.
-
O OSS SDK for Browser.js é usado principalmente em navegadores. Para evitar a exposição do par de AccessKey, use credenciais de acesso temporárias obtidas pelo Security Token Service (STS) para acessar o OSS.
As credenciais de acesso temporárias consistem em um par de AccessKey e um token de segurança. O par de AccessKey inclui um AccessKey ID e um AccessKey secret. Para obter detalhes sobre como adquirir credenciais de acesso temporárias, consulte Usar STS para autorização de acesso temporário.
Processar imagens com parâmetros de processamento
Processar uma imagem com um único parâmetro de processamento
<!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>
Processar uma imagem com vários parâmetros de processamento
Para usar vários parâmetros de processamento de imagens, separe-os com uma barra (/).
!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>
Processar imagens com estilos de imagem
-
Crie um estilo de imagem.
Adicione vários parâmetros de processamento a um estilo para executar operações complexas em imagens. Para mais informações, consulte Estilos de imagem.
-
Processe a imagem usando o estilo de imagem.
<!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>
Persistência de processamento de imagens
Por padrão, o serviço de processamento de imagens não salva as imagens processadas. Use o recurso de persistência de processamento de imagens para salvar a imagem processada no mesmo bucket da imagem de origem.
O código a seguir exemplifica o uso da persistência de processamento de imagens.
<!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>
Gerar URL assinada para arquivo com parâmetros de processamento de imagens
Ao acessar um arquivo privado pela URL, é necessária uma assinatura. Não adicione parâmetros de processamento de imagens diretamente a uma URL assinada. Para processar uma imagem privada, inclua os parâmetros de processamento na assinatura. O código a seguir fornece um exemplo:
<!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>