Tous les produits
Search
Centre de documentation

Object Storage Service:Traitement d'images (SDK PHP V1)

Dernière mise à jour :Aug 18, 2026

Image Processing (IMG) est un service de traitement d'images sécurisé, économique et hautement fiable fourni par Object Storage Service (OSS). Une fois vos images sources téléchargées sur OSS, vous pouvez les traiter à tout moment, depuis n'importe où et sur n'importe quel appareil connecté, en appelant des opérations API RESTful.

Notes

  • Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud dans la même région, utilisez un point de terminaison interne. Pour plus de détails sur les régions et points de terminaison pris en charge, consultez Régions et points de terminaison.

  • Cette rubrique illustre la création d'une instance OSSClient avec un point de terminaison OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Créer un OssClient.

  • Pour plus d'informations sur les paramètres de traitement d'images pris en charge, consultez Traitement d'images. Pour obtenir l'exemple de code complet, consultez GitHub.

Utiliser des paramètres de traitement d'images pour traiter des images

  • Traiter une image avec un seul paramètre de traitement d'image et l'enregistrer en tant que fichier 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);                           
  • Traiter une image avec plusieurs paramètres de traitement d'image et l'enregistrer en tant que fichier local

    Lorsque vous utilisez plusieurs paramètres de traitement d'image, séparez-les par des barres obliques (/).

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

Utiliser des styles d'image pour traiter des images

Vous pouvez créer un style d'image dans la console OSS et encapsuler plusieurs paramètres IMG dans ce style. Utilisez ensuite ce style pour traiter vos images. Pour plus d'informations, consultez Styles d'image.

Le code suivant montre comment traiter une image à l'aide d'un style d'image.

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

Persistance du traitement d'images

Par défaut, IMG ne sauvegarde pas les images traitées. Vous pouvez appeler l'opération ImgSaveAs pour enregistrer les images dans le bucket contenant les images sources.

Le code suivant montre comment effectuer une opération de persistance du traitement d'image.

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

Générer une URL signée pour un fichier avec des paramètres de traitement d'image

Les URL d'accès aux fichiers privés doivent être signées. OSS ne permet pas d'ajouter des paramètres de traitement d'image en les apposant simplement à une URL signée. Pour traiter un fichier privé, vous devez inclure les paramètres de traitement d'image dans la signature. L'exemple suivant illustre cette procédure :

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

Pour générer une URL signée pour un fichier contenant des paramètres de filigrane, reportez-vous à l'exemple suivant :

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