O Image Processing (IMG) é um serviço de processamento de imagens seguro, econômico e altamente confiável do Object Storage Service (OSS) que ajuda a processar grandes volumes de dados. Depois de enviar as imagens de origem para o OSS, você pode chamar operações da API RESTful para processar as imagens em qualquer dispositivo conectado à Internet, a qualquer hora e em qualquer lugar.
Para obter mais informações sobre os parâmetros de IMG com suporte, consulte Overview.
Observações de uso
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 obter mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.
Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar com credenciais do Security Token Service (STS), consulte Initialization.
Usar parâmetros de IMG para processar imagens
-
Use um único parâmetro de IMG para processar uma imagem e salve a imagem processada no seu computador local
# -*- coding: utf-8 -*- import os 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 region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4. region = "cn-hangzhou" # Specify the name of the bucket. bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region) # Specify the name of the image that you want to process. If the image is not stored in the root directory of the bucket, you must specify the path of the image. Example: example/example.jpg. key = 'yourObjectName' # Specify the name of the processed image. new_pic = 'LocalFileName' # If the image does not exist in the specified bucket, you must upload the image to the bucket. # bucket.put_object_from_file(key, 'yourLocalFile') # Resize the image to 100 × 100 pixels and then save the resized image to your local computer. style = 'image/resize,m_fixed,w_100,h_100' bucket.get_object_to_file(key, new_pic, process=style) # After the image is processed, you can delete the source image from the bucket if you no longer need the image. # bucket.delete_object(key) # If you no longer need the processed image, you can delete the processed image. # os.remove(new_pic) -
Use vários parâmetros de IMG para processar uma imagem e salve a imagem processada no seu computador local
O exemplo de código a seguir mostra como usar vários parâmetros de IMG para processar uma imagem. Os parâmetros de IMG são separados por barras (/).
# -*- coding: utf-8 -*- import os 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 region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4. region = "cn-hangzhou" # Specify the name of the bucket. bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region) # Specify the name of the bucket in which the source image is stored. Example: examplebucket. bucket_name = 'examplebucket' # Specify the name of the source image. If the image is not stored in the root directory of the bucket, you must specify the path of the image. Example: example/example.jpg. key = 'exampledir/example.jpg' # Specify the name of the processed image. new_pic = 'exampledir/newexample.jpg' # If the image that you want to process does not exist in the specified bucket, you must upload the image that is stored in the local path of the bucket. # bucket.put_object_from_file(key, 'D:\\localpath\\example.jpg') # Resize the image to 100 × 100 pixels, rotate the image 90 degrees, and then save the processed image to your local computer. style = 'image/resize,m_fixed,w_100,h_100/rotate,90' bucket.get_object_to_file(key, new_pic, process=style) # After the image is processed, you can delete the source image from the bucket if you no longer need the image. # bucket.delete_object(key) # If you no longer need the processed image, you can delete the image. # os.remove(new_pic)
Usar um estilo de imagem para processar imagens
É possível encapsular vários parâmetros de IMG em um estilo de imagem e, em seguida, usar esse estilo para processar uma imagem. Para obter mais informações, consulte Image styles. O código a seguir mostra como usar um estilo de imagem para processar uma imagem:
# -*- coding: utf-8 -*-
import os
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 region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
# Specify the name of the bucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# Specify the name of the bucket in which the source image is stored. Example: examplebucket.
bucket_name = 'examplebucket'
# Specify the name of the source image. If the image is not stored in the root directory of the bucket, you must specify the path of the image. Example: example/example.jpg.
key = 'exampledir/example.jpg'
# Specify the name of the processed image.
new_pic = 'exampledir/newexample.jpg'
# If the image that you want to process does not exist in the specified bucket, you must upload the image that is stored in the local path of the bucket.
# bucket.put_object_from_file(key, 'D:\\localpath\\example.jpg')
# Use a custom image style to process the image. Set yourCustomStyleName to the name of the image style that you created in the OSS console.
style = 'style/yourCustomStyleName'
# Save the processed image to your local computer.
bucket.get_object_to_file(key, new_pic, process=style)
# After the image is processed, you can delete the source image from the bucket if you no longer need the image.
# bucket.delete_object(key)
# If you no longer need the processed image, you can delete the image.
# os.remove(new_pic)
Salvar imagens processadas
Chame a operação ImgSaveAs para salvar imagens processadas em um bucket específico. O exemplo de código a seguir mostra como salvar uma imagem processada:
# -*- coding: utf-8 -*-
import os
import base64
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 region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
# Specify the name of the bucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# Specify the name of the bucket in which the source image is stored.
source_bucket_name = 'srcbucket'
# Specify the name of the bucket in which you want to save the processed image. The bucket must be within the same region as the bucket in which the source image is stored.
target_bucket_name = 'destbucket'
# Specify the name of the source image. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: example/example.jpg.
source_image_name = 'example/example.jpg'
# Resize the image to 100 × 100 pixels.
style = 'image/resize,m_fixed,w_100,h_100'
# Specify the name of the processed image. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg.
target_image_name = 'exampledir/example.jpg'
process = "{0}|sys/saveas,o_{1},b_{2}".format(style,
oss2.compat.to_string(base64.urlsafe_b64encode(oss2.compat.to_bytes(target_image_name))),
oss2.compat.to_string(base64.urlsafe_b64encode(oss2.compat.to_bytes(target_bucket_name))))
result = bucket.process_object(source_image_name, process)
print(result)
Gerar uma URL de objeto assinada que inclui parâmetros de IMG
É necessário assinar as URLs de objetos privados. Não é possível adicionar parâmetros de IMG ao final de uma URL assinada. Para processar um objeto de imagem privado, adicione os parâmetros de IMG à assinatura. O exemplo de código a seguir mostra como adicionar parâmetros de IMG a uma assinatura:
# -*- 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 region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
# Specify the name of the bucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# Specify the name of the bucket. Example: examplebucket.
bucket_name = 'examplebucket'
# Specify the name of the bucket in which the image is stored. If the image is not stored in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg.
key = 'exampledir/example.jpg'
# If the image is not stored in the specified bucket, you must upload the image to the bucket.
# bucket.put_object_from_file(key, 'D:\\localpath\\example.jpg')
# Resize the image to 100 × 100 pixels and rotate the image 90 degrees.
style = 'image/resize,m_fixed,w_100,h_100/rotate,90'
# Generate a signed object URL that includes IMG parameters. Set the validity period of the URL to 600. Unit: seconds.
url = bucket.sign_url('GET', key, 10 * 60, params={'x-oss-process': style})
print(url)
Referências
Para obter o exemplo de código completo sobre como usar o IMG, visite o GitHub.