Todos los productos
Search
Centro de documentos

Object Storage Service:Procesamiento de imágenes (PHP SDK V1)

Última actualización: Sep 03, 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 imágenes. Una vez que cargue las imágenes originales en OSS, podrá invocar operaciones de la API RESTful para procesarlas en cualquier momento, desde cualquier lugar y en cualquier dispositivo conectado.

Notas

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

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

  • Para obtener más información sobre los parámetros de procesamiento de imágenes compatibles, consulte Image processing. Para ver el código de ejemplo completo, consulte GitHub.

Uso de parámetros de procesamiento de imágenes

  • Procesar una imagen con un solo parámetro y guardarla como archivo local

    <?php
    if (is_file(__DIR__ . '/../autoload.php')) {
        require_once __DIR__ . '/../autoload.php';
    }
    if (is_file(__DIR__ . '/../vendor/autoload.php')) {
        require_once __DIR__ . '/../vendor/autoload.php';
    }
    use OSS\Credentials\EnvironmentVariableCredentialsProvider;
    use OSS\OssClient;
    
    // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
    $provider = new EnvironmentVariableCredentialsProvider();
    // Set yourEndpoint to 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 = "yourEndpoint";
    // Set the bucket name. For example, examplebucket.
    $bucket= "examplebucket";
    // Set the full path of the object. For example, exampledir/exampleobject.jpg. The full path cannot include the bucket name.
    $object = "exampledir/exampleobject.jpg";
    // Set the full path of the local file. For example, D:\\localpath\\example-resize.jpg. If the specified local file exists, it is overwritten. If it does not exist, a new file is created.
    // If you specify only the local file name, such as example-resize.jpg, without a full path, the file is saved by default to the local path of the project where the sample program resides.
    $download_file = "D:\\localpath\\example-resize.jpg";
    
    $config = array(
            "provider" => $provider,
            "endpoint" => $endpoint,
            "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
            "region"=> "cn-hangzhou"
        );
        $ossClient = new OssClient($config);
    // If the source image is not in the specified bucket, upload the image to the bucket.
    // $ossClient->uploadFile($bucket, $object, "D:\\localpath\\exampleobject.jpg");
    
    // Resize the image to a fixed width and height of 100 px.
    $options = array(
        OssClient::OSS_FILE_DOWNLOAD => $download_file,
        OssClient::OSS_PROCESS => "image/resize,m_fixed,h_100,w_100" );
    // Name the processed image example-resize.jpg and save it to a local path.
    $ossClient->getObject($bucket, $object, $options);
    
    // After the image is processed, delete the source image from the bucket if it is no longer needed.
    // $ossClient->deleteObject($bucket, $object);                           
  • Procesar una imagen con varios parámetros y guardarla como archivo local

    Cuando utilice varios parámetros de procesamiento de imágenes, sepárelos con barras diagonales (/).

    <?php
    if (is_file(__DIR__ . '/../autoload.php')) {
        require_once __DIR__ . '/../autoload.php';
    }
    if (is_file(__DIR__ . '/../vendor/autoload.php')) {
        require_once __DIR__ . '/../vendor/autoload.php';
    }
    use OSS\Credentials\EnvironmentVariableCredentialsProvider;
    use OSS\OssClient;
    
    // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
    $provider = new EnvironmentVariableCredentialsProvider();
    // Set yourEndpoint to 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 = "yourEndpoint";
    // Set the bucket name. For example, examplebucket.
    $bucket= "examplebucket";
    // Set the full path of the object. For example, exampledir/exampleobject.jpg. The full path cannot include the bucket name.
    $object = "exampledir/exampleobject.jpg";
    // Set the full path of the local file. For example, D:\\localpath\\example-new.jpg. If the specified local file exists, it is overwritten. If it does not exist, a new file is created.
    // If you specify only the local file name, such as example-new.jpg, without a full path, the file is saved by default to the local path of the project where the sample program resides.
    $download_file = "D:\\localpath\\example-new.jpg";
    
    $config = array(
            "provider" => $provider,
            "endpoint" => $endpoint,
            "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
            "region"=> "cn-hangzhou"
        );
        $ossClient = new OssClient($config);
    // If the source image is not in the specified bucket, upload the image to the bucket.
    // $ossClient->uploadFile($bucket, $object, "D:\\localpath\\exampleobject.jpg");
    
    // Resize the image to a fixed width and height of 100 px, and then rotate it 90 degrees.
    $style = "image/resize,m_fixed,w_100,h_100/rotate,90";
    
    $options = array(
        OssClient::OSS_FILE_DOWNLOAD => $download_file,
        OssClient::OSS_PROCESS => $style);
    
    // Name the processed image example-new.jpg and save it to a local path.
    $ossClient->getObject($bucket, $object, $options);
    
    // After the image is processed, delete the source image from the bucket if it is no longer needed.
    // $ossClient->deleteObject($bucket, $object);                              

Uso de estilos de imagen

Puede crear un estilo de imagen en la consola de OSS y encapsular varios parámetros de IMG en dicho estilo. Después, utilice el estilo para procesar imágenes. Para obtener más información, consulte Image styles.

El siguiente código muestra cómo procesar una imagen mediante un estilo.

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// Set yourEndpoint to 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 = "yourEndpoint";
// Set the bucket name. For example, examplebucket.
$bucket= "examplebucket";
// Set the full path of the object. For example, exampledir/exampleobject.jpg. The full path cannot include the bucket name.
$object = "exampledir/exampleobject.jpg";
// Set the full path of the local file. For example, D:\\localpath\\example-new.jpg. If the specified local file exists, it is overwritten. If it does not exist, a new file is created.
// If you specify only the local file name, such as example-new.jpg, without a full path, the file is saved by default to the local path of the project where the sample program resides.
$download_file = "D:\\localpath\\example-new.jpg";

$config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

// If the source image is not in the specified bucket, upload the image to the bucket.
// $ossClient->uploadFile($bucket, $object, "D:\\localpath\\exampleobject.jpg");

// Process the image using a custom style.
// Set yourCustomStyleName to the name of the image style that you created in the OSS console.
$style = "style/yourCustomStyleName";

$options = array(
    OssClient::OSS_FILE_DOWNLOAD => $download_file,
    OssClient::OSS_PROCESS => $style);

// Name the processed image example-new.jpg and save it to a local path.
$ossClient->getObject($bucket, $object, $options);

// After the image is processed, delete the source image from the bucket if it is no longer needed.
// $ossClient->deleteObject($bucket, $object);                              

Persistencia del procesamiento de imágenes

De forma predeterminada, IMG no guarda las imágenes procesadas. Puede invocar la operación ImgSaveAs para guardar las imágenes en el bucket donde se almacenan las imágenes originales.

El siguiente código muestra cómo ejecutar una operación de persistencia de procesamiento de imágenes.

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;

// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// Set yourEndpoint to 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 = "yourEndpoint";
// Set the bucket name. For example, examplebucket.
$bucket= "examplebucket";
// Set the full path of the source object. For example, exampledir/exampleobject.jpg. The full path cannot include the bucket name.
$object = "exampledir/exampleobject.jpg";
// Set the full path of the destination object. For example, example-new.jpg.
$save_object = "example-new.jpg";

function base64url_encode($data)
{
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

$config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);
// If the source image is not in the specified bucket, upload the image to the bucket.
// $ossClient->uploadFile($bucket, $object, "D:\\localpath\\exampleobject.jpg");

// Resize the image to a fixed width and height of 100 px, and then rotate it 90 degrees.
$style = "image/resize,m_fixed,w_100,h_100/rotate,90";

$process = $style.
           '|sys/saveas'.
           ',o_'.base64url_encode($save_object).
           ',b_'.base64url_encode($bucket);

// Name the processed image example-new.png and save it to the current bucket.
$result = $ossClient->processObject($bucket, $object, $process);
// Print the processing result.
print($result);

Generación de una URL firmada para un archivo con parámetros de procesamiento de imágenes

Las URL de acceso para archivos privados deben estar firmadas. OSS no admite agregar parámetros de procesamiento de imágenes anexándolos a una URL firmada. Para procesar un archivo privado, debe añadir los parámetros de procesamiento de imágenes a la firma. A continuación se proporciona un ejemplo:

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;

// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// Set yourEndpoint to 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 = "yourEndpoint";
// Set the bucket name. For example, examplebucket.
$bucket= "examplebucket";
// Set the full path of the object. For example, exampledir/exampleobject.jpg. The full path cannot include the bucket name.
$object = "exampledir/exampleobject.jpg";

$config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

// Generate a signed URL that includes image processing parameters. The URL is valid for 3,600 seconds. You can use a browser to access the URL.
$timeout = 3600;

$options = array(
    // Resize the image to a fixed width and height of 100 px.
    OssClient::OSS_PROCESS => "image/resize,m_fixed,h_100,w_100" );

$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
print("rtmp url: \n" . $signedUrl);           

Para generar una URL firmada para un archivo que contiene parámetros de marca de agua, consulte el siguiente ejemplo:

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;

// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// Set yourEndpoint to 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 = "yourEndpoint";
// Set the bucket name. For example, examplebucket.
$bucket= "examplebucket";
// Set the full path of the object. For example, exampledir/exampleobject.jpg. The full path cannot include the bucket name.
$object = "exampledir/exampleobject.jpg";

$config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
        
    );
    $ossClient = new OssClient($config);

// Generate a signed URL that contains watermark parameters. The URL is valid for 3,600 seconds. You can use a browser to access the URL.
$timeout = 3600;

function base64url_encode($data)
{
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
// Set the text of the watermark, such as Hello World, or the full path of the watermark image, such as panda.jpg.
// When you add a watermark image to an image, make sure that the watermark image is stored in the same bucket as the source image.
$content = "Hello World";
$string = base64url_encode($content);

$options = array(
    // Add a watermark to the image.
    OssClient::OSS_PROCESS => "image/watermark,text_".$string
);

$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
print("rtmp url: \n" . $signedUrl);