O Image Processing (IMG) é um serviço seguro, econômico e altamente confiável do Object Storage Service (OSS) para processamento de imagens. Após carregar as imagens originais no OSS, chame operações da API RESTful para processá-las a qualquer momento, em qualquer lugar e em qualquer dispositivo conectado.
Observações
Este tópico usa o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços do Alibaba Cloud na mesma região, use um endpoint interno. Para obter detalhes sobre regiões e endpoints compatíveis, consulte Regiões e endpoints.
Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Criar um OssClient.
Para mais informações sobre os parâmetros de processamento de imagens compatíveis, consulte Processamento de imagens. Para ver o código de exemplo completo, acesse o GitHub.
Usar parâmetros de processamento de imagens
-
Processe uma imagem com um único parâmetro e salve-a como 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 e salve-a como arquivo local
Ao usar múltiplos 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);
Usar estilos de imagem
Crie um estilo de imagem no console do OSS para encapsular vários parâmetros IMG. Depois, use o estilo para processar as imagens. Para mais informações, consulte Estilos de imagem.
O código a seguir mostra como processar uma imagem com um 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);
Persistência do processamento de imagens
Por padrão, o IMG não salva as imagens processadas. Chame a operação ImgSaveAs para salvá-las no bucket onde as imagens originais 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);
Gerar URL assinada com parâmetros de processamento de imagens
URLs de acesso a arquivos privados exigem assinatura. O OSS não permite adicionar parâmetros de processamento de imagens diretamente a uma URL assinada. Para processar um arquivo privado, inclua os parâmetros de processamento de imagens na assinatura. Veja o exemplo no código 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 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 com 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);