Algumas imagens podem conter dados no formato Exchangeable Image File Format (EXIF), que incluem atributos da imagem e configurações de captura. Os dados EXIF abrangem informações como taxa de compressão, orientação, resolução horizontal e vertical. Para obter os dados EXIF de uma imagem, adicione o parâmetro info à URL da imagem.
Parâmetros
Ação: info
As informações retornadas estão no formato JSON. Cada campo na resposta utiliza a estrutura "FieldName": {"value": "field value"}, e todos os valores dos campos são strings.
|
Campo |
Descrição |
Sempre retornado |
|
|
Tamanho do arquivo de imagem, em bytes. |
Sim |
|
|
Formato da imagem, como jpg, png ou gif. |
Sim |
|
|
Número de quadros na imagem. |
Sim |
|
|
Altura da imagem, em pixels. |
Sim |
|
|
Largura da imagem, em pixels. |
Sim |
|
|
Unidade de resolução da imagem. Retornado apenas se a imagem possuir metadados de resolução. |
Não |
|
|
Resolução horizontal da imagem, retornada como fração (por exemplo, 1/1 ou 96/1). Retornado apenas se a imagem possuir metadados de resolução. |
Não |
|
|
Resolução vertical da imagem, retornada como fração (por exemplo, 1/1 ou 96/1). Retornado apenas se a imagem possuir metadados de resolução. |
Não |
|
Campos EXIF, como |
Dados EXIF da imagem. Os campos retornados dependem dos dados EXIF presentes na imagem. Para mais informações, consulte Exif Version 2.31. |
Não |
Não é possível usar a ação info com outras ações em uma solicitação de processamento de imagem. Por exemplo, não use image/resize,s_700,limit_0/info para redimensionar uma imagem e consultar informações sobre a imagem redimensionada simultaneamente.
Limites
A ação info permite consultar informações apenas de imagens nos formatos JPG, PNG, BMP, GIF, WebP, TIFF e HEIC.
Embora o formato PNG seja suportado, não é possível usar a ação info para consultar dados EXIF de imagens PNG.
Operações
Configure parâmetros de processamento de imagem usando URLs, SDKs do OSS ou APIs RESTful. URLs são adequadas para imagens acessíveis publicamente. Para imagens privadas, recomendamos o uso de SDKs do OSS ou APIs RESTful. Para detalhes, consulte Image processing methods.
Obter informações sobre imagens de leitura pública ou leitura/gravação pública
Para obter informações sobre imagens de leitura pública ou leitura/gravação pública, adicione parâmetros de processamento de imagem diretamente às URLs.
-
Consultar informações de uma imagem sem dados EXIF
https://image-demo.oss-cn-hangzhou.aliyuncs.com/example.jpg?x-oss-process=image/info
Ao adicionar o parâmetro info,
FileSize,Format,FrameCount,ImageHeighteImageWidthconstituem as informações básicas da imagem e são retornados para todas as imagens suportadas.ResolutionUnit,XResolutioneYResolutionsão retornados apenas se a imagem possuir metadados de resolução. Todos os outros campos EXIF aparecem somente se a imagem contiver dados EXIF. A imagem no exemplo a seguir não contém dados EXIF, mas possui metadados de resolução. Portanto, a resposta inclui os campos de resolução além das informações básicas.{ "FileSize": {"value": "21839"}, "Format": {"value": "jpg"}, "FrameCount": {"value": "1"}, "ImageHeight": {"value": "267"}, "ImageWidth": {"value": "400"}, "ResolutionUnit": {"value": "1"}, "XResolution": {"value": "1/1"}, "YResolution": {"value": "1/1"} } -
Consultar informações de uma imagem com dados EXIF
https://image-demo.oss-cn-hangzhou.aliyuncs.com/f.jpg?x-oss-process=image/info
Se você adicionar o parâmetro info à URL de uma imagem com dados EXIF, a resposta incluirá as informações básicas e os dados EXIF da imagem. Para mais informações, consulte Exif Version 2.31.
{ "Compression": {"value": "6"}, "DateTime": {"value": "2015:02:11 15:38:27"}, "ExifTag": {"value": "2212"}, "FileSize": {"value": "23471"}, "Format": {"value": "jpg"}, "FrameCount": {"value": "1"}, "GPSLatitude": {"value": "0deg "}, "GPSLatitudeRef": {"value": "North"}, "GPSLongitude": {"value": "0deg "}, "GPSLongitudeRef": {"value": "East"}, "GPSMapDatum": {"value": "WGS-84"}, "GPSTag": {"value": "4292"}, "GPSVersionID": {"value": "2 2 0 0"}, "ImageHeight": {"value": "333"}, "ImageWidth": {"value": "424"}, "JPEGInterchangeFormat": {"value": "4518"}, "JPEGInterchangeFormatLength": {"value": "3232"}, "Orientation": {"value": "7"}, "ResolutionUnit": {"value": "2"}, "Software": {"value": "Microsoft Windows Photo Viewer 6.1.7600.16385"}, "XResolution": {"value": "96/1"}, "YResolution": {"value": "96/1"}}
Obter informações sobre imagens privadas
Para obter informações sobre imagens privadas, utilize o Alibaba Cloud SDK ou a API REST.
Usar Alibaba Cloud SDK
Os exemplos de código a seguir demonstram como usar SDKs para linguagens de programação comuns para obter informações sobre imagens. Para mais informações sobre como obter informações sobre imagens usando SDKs para outras linguagens de programação, consulte Referência do SDK.
Java
É necessário Java SDK versão 3.17.4 ou superior.
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyuncs.exceptions.ClientException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class Demo{
public static void main(String[] args) throws ClientException, ClientException {
// yourEndpoint Specify the endpoint of the region in which the bucket is located.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the endpoint of the region. For example, cn-hangzhou.
String region = "cn-hangzhou";
// 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.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket.
String bucketName = "examplebucket";
// Specify the name of the image if it is stored in the root directory of the bucket. If it is stored elsewhere, you must specify the full path of the image. Example: exampledir/example.jpg.
String key = "example.jpg";
// Create an OSSClient instance.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Create a request to obtain information about the image.
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
getObjectRequest.setProcess("image/info");
// Use getObject and input instructions via process parameters.
OSSObject ossObject = ossClient.getObject(getObjectRequest);
// Read and print information.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = ossObject.getObjectContent().read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
String imageInfo = baos.toString("UTF-8");
System.out.println("Image Info:");
System.out.println(imageInfo);
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} finally {
// Shut down OSSClient
ossClient.shutdown();
}
}
}
PHP
É necessário PHP SDK versão 2.7.0 ou superior.
<?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;
try {
// 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.
$provider = new 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 name of the bucket. Example: examplebucket.
$bucket = 'examplebucket';
// Specify the name of the image if it is stored in the root directory of the bucket. If it is stored elsewhere, you must specify the full path of the image. Example: exampledir/example.jpg.
$key = 'example.jpg';
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
// Specify the Region ID.
"region" => "cn-hangzhou"
);
$ossClient = new OssClient($config);
// Create a request to obtain information about the image.
$options[$ossClient::OSS_PROCESS] = "image/info";
$result = $ossClient->getObject($bucket,$key,$options);
var_dump($result);
} catch (OssException $e) {
printf($e->getMessage() . "\n");
return;
}
Go
É necessário Go SDK 3.0.2 ou superior.
package main
import (
"fmt"
"io"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// 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.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// 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. Specify your actual endpoint.
// Specify the Region ID. Example: cn-hangzhou.
client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region("cn-hangzhou"))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of the bucket. Example: examplebucket.
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of the image if it is stored in the root directory of the bucket. If it is stored elsewhere, you must specify the full path of the image. Example: exampledir/example.jpg.
// Create a request to obtain information about the image by using oss.Process.
body, err := bucket.GetObject("example.jpg", oss.Process("image/info"))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
defer body.Close()
data, err := io.ReadAll(body)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
fmt.Println("data:", string(data))
}
Usar API RESTful
Caso seu negócio exija alto nível de personalização, chame diretamente as APIs RESTful. Para chamar uma API diretamente, inclua o cálculo da assinatura no código. Para mais informações, consulte (Recommended) Include a V4 signature.
Adicione parâmetros IMG ou de estilo de imagem às solicitações GetObject para processar imagens.
GET /oss.jpg?x-oss-process=image/info HTTP/1.1
Host: oss-example.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: OSS4-HMAC-SHA256 Credential=LTAI********************/20250417/cn-hangzhou/oss/aliyun_v4_request,Signature=a7c3554c729d71929e0b84489addee6b2e8d5cb48595adfc51868c299c0c218e
Perguntas frequentes
Como consulto informações sobre uma imagem privada?
Para consultar informações sobre uma imagem privada, adicione o parâmetro info a uma URL assinada usando SDKs do OSS e, em seguida, use a URL para acessar a imagem.
-
Gere uma URL assinada.
O exemplo de código a seguir mostra como usar o OSS SDK for Java para gerar uma URL assinada:
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.GeneratePresignedUrlRequest; import java.net.URL; import java.util.Date; public class Demo { public static void main(String[] args) throws Throwable { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. String region = "cn-hangzhou"; // For security purposes, we recommend that you do not save access credentials in the project code. In this example, access credentials are obtained from environment variables. Before you run the sample code, make sure that the environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. String objectName = "exampleobject.jpg"; // Create an OSSClient instance. // Call the shutdown method to release resources when the OSSClient is no longer in use. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); // Explicitly declare the use of the V4 signature algorithm. clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Query information about the image object. String style = "image/info"; // Set the validity period of the signed URL to 10 minutes. Date expiration = new Date(new Date().getTime() + 1000 * 60 * 10 ); GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET); req.setExpiration(expiration); req.setProcess(style); URL signedUrl = ossClient.generatePresignedUrl(req); System.out.println(signedUrl); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } } Use a URL assinada para acessar a imagem em um navegador e consultar as informações da imagem.