Todos los productos
Search
Centro de documentos

Object Storage Service:IMG (OSS SDK for Python 1.0)

Última actualización: Sep 17, 2026

Image Processing (IMG) es un servicio de procesamiento de imágenes seguro, rentable y altamente confiable que proporciona Object Storage Service (OSS) para ayudarle a procesar grandes volúmenes de datos. Después de cargar las imágenes originales en OSS, puede llamar a operaciones de la API RESTful para procesarlas desde cualquier dispositivo conectado a Internet, en cualquier momento y lugar.

Para obtener más información sobre los parámetros de IMG compatibles, consulte Descripción general.

Notas de uso

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Si desea acceder a OSS desde otros servicios de Alibaba Cloud ubicados en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Initialization.

Usar parámetros de IMG para procesar imágenes

  • Use un solo parámetro de IMG para procesar una imagen y guarde el resultado en su computadora 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)
  • Utilice varios parámetros de IMG para procesar una imagen y guarde el resultado en su computadora local.

    A continuación se muestra un ejemplo de código sobre cómo usar varios parámetros de IMG para procesar una imagen. Los parámetros de IMG se separan con barras diagonales (/).

    # -*- 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 un estilo de imagen para procesar imágenes

Puede agrupar varios parámetros de IMG dentro de un estilo de imagen y luego utilizar ese estilo para procesarla. Para obtener más información, consulte Image styles. El siguiente código muestra un ejemplo de cómo usar un estilo de imagen para procesar una imagen:

# -*- 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)

Guardar imágenes procesadas

Puede llamar a la operación ImgSaveAs para guardar las imágenes procesadas en un bucket específico. A continuación se muestra un ejemplo de código sobre cómo guardar una imagen procesada:

# -*- 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)

Generar una URL firmada de objeto que incluya parámetros de IMG

Las URL de los objetos privados deben estar firmadas. No es posible agregar parámetros de IMG al final de una URL firmada. Si desea procesar un objeto de imagen privado, agregue los parámetros de IMG a la firma. A continuación se muestra un ejemplo de código sobre cómo agregar parámetros de IMG a una firma:

# -*- 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)

Referencias

Para consultar el código de ejemplo completo sobre cómo usar IMG, visite GitHub.