Todos os produtos
Search
Central de documentação

Object Storage Service:Image processing (PHP SDK V1)

Última atualização: Sep 24, 2026

O Image Processing (IMG) é um service de processamento de imagens seguro, econômico e altamente confiável, fornecido pelo Object Storage Service (OSS) para ajudar você a processar imagens. Após fazer o upload das imagens de origem para o OSS, você pode chamar operações da API RESTful para processar as imagens a qualquer momento, em qualquer lugar e em qualquer dispositivo conectado.

Observações

  • Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros services da Alibaba Cloud na mesma região, use um endpoint interno. Para obter detalhes sobre as regiões e endpoints suportados, consulte {{XREF_0}}.

  • Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como o uso de um domínio personalizado ou a autenticação com credenciais do Security Token Service (STS), consulte {{XREF_1}}.

  • Para obter mais informações sobre os parâmetros de processamento de imagens suportados, consulte {{XREF_2}}. Para ver o código de exemplo completo, acesse o GitHub.

Utilize parâmetros de processamento de imagens para processar imagens

  • Processe uma imagem com um único parâmetro de processamento de imagens e salve-a como um arquivo 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);                           
  • Processe uma imagem com vários parâmetros de processamento de imagens e salve-a como um arquivo local

    Ao usar vários parâmetros de processamento de imagens, separe-os com barras (/).

    <?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);                              

Utilize estilos de imagem para processar imagens

Você pode criar um estilo de imagem no console do OSS e encapsular vários parâmetros do IMG no estilo. Em seguida, utilize o estilo para processar as imagens. Para obter mais informações, consulte {{XREF_3}}.

O código a seguir mostra como processar uma imagem usando um estilo de imagem.

<?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);                              

Persistência do processamento de imagens

Por padrão, o IMG não salva as imagens processadas. Você pode chamar a operação ImgSaveAs para salvar as imagens no bucket onde as imagens de origem estão armazenadas.

O código a seguir mostra como executar uma operação de persistência de processamento de imagens.

<?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);

Gere uma URL assinada para um arquivo com parâmetros de processamento de imagens

As URLs de acesso para arquivos privados devem ser assinadas. O OSS não oferece suporte à adição de parâmetros de processamento de imagens anexando-os a uma URL assinada. Para processar um arquivo privado, você deve adicionar os parâmetros de processamento de imagens à assinatura. O código a seguir fornece um exemplo:

<?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 gerar uma URL assinada para um arquivo que contém parâmetros de marca d'água, consulte o exemplo a seguir:

<?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);