No Object Storage Service (OSS), um estilo de imagem permite executar uma série de operações de processamento, como redimensionamento, recorte, rotação e adição de marcas d'água. Crie um estilo de imagem para definir essas operações e aplique-o às imagens em um bucket para garantir transformação e processamento ágeis.
Observações
Para obter mais informações sobre os parâmetros de processamento de imagem compatíveis com estilos de imagem, consulte Processamento de imagens.
Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais detalhes sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso (Python SDK V1).
Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação via Security Token Service (STS), consulte Inicialização.
-
Permissões
Uma conta Alibaba Cloud possui, por padrão, as permissões necessárias para operações de estilo de imagem. Para executar essas operações como usuário do Resource Access Management (RAM) ou via STS, você deve ter as permissões correspondentes:
Para criar um estilo de imagem, é necessária a permissão
oss:PutStyle.Para consultar informações de um estilo específico em um bucket, é necessária a permissão
oss:GetStyle.Para listar todos os estilos criados em um bucket, é necessária a permissão
oss:ListStyle.Para excluir um estilo específico de um bucket, é necessária a permissão
oss:DeleteStyle.
Para mais informações, consulte Conceder políticas de acesso personalizadas a um usuário RAM.
Criar um estilo de imagem
Você pode criar até 50 estilos de imagem por bucket. O código abaixo demonstra como criar um estilo:
# -*- 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 where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region of the endpoint. Example: cn-hangzhou. This parameter is required if you use the V4 signature algorithm.
region = "cn-hangzhou"
# Replace examplebucket with the name of the bucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# Specify the name of the image style, such as imagestyle.
style = 'imagestyle'
# Specify the operation of the image style, such as resizing the image to a width of 200 pixels.
content = 'image/resize,w_200'
# Create an image style.
result = bucket.put_bucket_style(style, content)
print('The style is created. The status code is: ' + str(result.status))
Após criar o estilo, use-o para processar imagens. Para mais detalhes, consulte Usar estilos de imagem para processar imagens.
Consultar um estilo de imagem específico
O exemplo a seguir mostra como consultar informações de um estilo de imagem definido em um bucket.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run this code, set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set endpoint to the endpoint of the region where the bucket is located. For example, for the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Set region to the region that corresponds to your endpoint, such as cn-hangzhou. Note: This parameter is required for V4 signatures.
region = "cn-hangzhou"
# Replace examplebucket with your bucket name.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# Specify the name of the image style, such as imagestyle.
style = 'imagestyle'
# Query information about the specified image style in the examplebucket bucket.
result = bucket.get_bucket_style(style)
print('name: ' + result.name)
print('content: ' + result.content)
Consultar todos os estilos de imagem
O código abaixo demonstra como listar todos os estilos de imagem criados em um bucket.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before running this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region that corresponds to the endpoint, such as cn-hangzhou. Note: This parameter is required for V4 signatures.
region = "cn-hangzhou"
# Replace examplebucket with your bucket name.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# Query all created image styles in the examplebucket bucket.
result = bucket.list_bucket_style()
for sty in result.styles:
print('name: ' + sty.name)
print('content: ' + sty.content)
Excluir um estilo de imagem específico
Use o código a seguir para excluir um estilo de imagem específico do bucket examplebucket.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run this code, set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set endpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Set the region that corresponds to the endpoint, such as cn-hangzhou. This parameter is required for V4 signatures.
region = "cn-hangzhou"
# Replace examplebucket with your bucket name.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# Specify the name of the image style, such as imagestyle.
style = 'imagestyle'
# Delete the specified image style.
result = bucket.delete_bucket_style(style)
print('Style deleted successfully. Return status: ' + str(result.status))
Referências
Para obter mais informações sobre a operação de API para criar um estilo de imagem, consulte PutStyle.
Para obter mais informações sobre a operação de API para consultar um estilo específico em um bucket, consulte GetStyle.
Para obter mais informações sobre a operação de API para listar todos os estilos em um bucket, consulte ListStyle.
Para obter mais informações sobre a operação de API para excluir um estilo específico de um bucket, consulte DeleteStyle.