La función de reconocimiento de códigos QR detecta múltiples códigos QR o códigos de barras en diversas imágenes. Devuelve el cuadro delimitador y el contenido de texto de cada código detectado. El sistema anota el cuadro delimitador de cada código QR o código de barras y muestra su contenido de texto en la salida.
Descripción general
Intelligent Media Management (IMM) ofrece la función de reconocimiento de códigos QR, que permite detectar la posición y el contenido de uno o más códigos QR o códigos de barras en archivos de imagen, como fotografías y capturas de pantalla. Esta función devuelve la información de posición y el texto que contienen los códigos. La información de posición incluye la coordenada X de la esquina superior izquierda, la coordenada Y de la esquina superior izquierda, el ancho y la altura, como se muestra en la siguiente figura.
-
Código QR

-
Código de barras

Puede utilizar la función de reconocimiento de códigos QR para implementar el escaneo y la lectura de códigos QR o códigos de barras en sus aplicaciones empresariales. También puede desarrollar funciones para bloquear o pixelar códigos QR o códigos de barras en imágenes mediante esta capacidad de reconocimiento.
Escenarios
Pagos con códigos QR: Los pagadores pueden escanear un código QR para completar sus pagos.
Marketing y publicidad con códigos QR: Los especialistas en marketing y publicistas pueden agregar códigos QR a carteles y empaques de productos para promocionarlos.
Notas de uso
Solo se admite el procesamiento síncrono (x-oss-process).
Se pueden detectar hasta cinco códigos QR en una sola imagen.
Se denegará el acceso anónimo.
Cómo usar
Requisitos previos
Tiene activated the Intelligent Media Management (IMM) service.
Vincule un proyecto de IMM. Para obtener instrucciones sobre cómo vincular un proyecto en la consola de Object Storage Service (OSS), consulte Getting Started. Para vincular un proyecto mediante una API, consulte AttachOSSBucket - Attach an OSS bucket.
Reconocimiento de códigos QR
Acción: image/codes
Java
Utilice Java SDK 3.17.4 o posterior.
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 {
// Set endpoint to the endpoint of the region where the bucket is located.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region information that corresponds to the endpoint, for example, cn-hangzhou.
String region = "cn-hangzhou";
// 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.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the bucket name.
String bucketName = "examplebucket";
// If the image is in the root directory of the bucket, specify the image name. If the image is not in the root directory, specify the full path, such as exampledir/example.jpg.
String key = "example.jpg";
// Create an OSSClient instance.
// When the OSSClient instance is no longer in use, call the shutdown method to release resources.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Build the processing instruction for QR code recognition.
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
getObjectRequest.setProcess("image/codes");
// Use the getObject method and pass the processing instruction in the process parameter.
OSSObject ossObject = ossClient.getObject(getObjectRequest);
// Read and print the 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 imageCodes = baos.toString("UTF-8");
System.out.println("Image Codes:");
System.out.println(imageCodes);
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} finally {
// Shut down the OSSClient.
ossClient.shutdown();
}
}
}
Python
Utilice Python SDK 2.18.4 o posterior.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# 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.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set endpoint 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 = 'https://oss-cn-hangzhou.aliyuncs.com'
# Specify the general-purpose region ID of Alibaba Cloud.
region = 'cn-hangzhou'
bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)
# If the image is in the root directory of the bucket, specify the image name. If the image is not in the root directory, specify the full path, such as exampledir/example.jpg.
key = 'example.jpg'
# Build the processing instruction for QR code recognition.
process = 'image/codes'
try:
# Use the get_object method and pass the processing instruction in the process parameter.
result = bucket.get_object(key, process=process)
# Read and print the information.
image_codes = result.read().decode('utf-8')
print("Image Codes:")
print(image_codes)
except oss2.exceptions.OssError as e:
print("Error:", e)
Go
Utilice Go SDK 3.0.2 o posterior.
package main
import (
"fmt"
"io"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain temporary 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, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Set endpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Set the endpoint based on your actual region.
// Specify the general-purpose region ID of Alibaba Cloud, for 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 bucket name, for example, examplebucket.
bucketName := "examplebucket"
bucket, err := client.Bucket(bucketName)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// If the image is in the root directory of the bucket, specify the image name. If the image is not in the root directory, specify the full path, such as exampledir/example.jpg.
// Use the oss.Process method to build the processing instruction for QR code recognition.
body, err := bucket.GetObject("example.jpg", oss.Process("image/codes"))
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))
}
PHP
Utilice PHP SDK 2.7.0 o posterior.
<?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 this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// Set endpoint 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 = 'https://oss-cn-hangzhou.aliyuncs.com';
// Specify the bucket name, for example, examplebucket.
$bucket = 'examplebucket';
// If the image is in the root directory of the bucket, specify the image name. If the image is not in the root directory, specify the full path, such as exampledir/example.jpg.
$key = 'example.jpg';
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
// Specify the general-purpose region ID of Alibaba Cloud.
"region" => "cn-hangzhou"
);
$ossClient = new OssClient($config);
// Build the processing instruction for QR code recognition.
$options[$ossClient::OSS_PROCESS] = "image/codes";
$result = $ossClient->getObject($bucket,$key,$options);
var_dump($result);
} catch (OssException $e) {
printf($e->getMessage() . "\n");
return;
}
Parámetros
Acción: image/codes
Para obtener más información sobre los parámetros de respuesta, consulte DetectImageCodes - Detect QR codes in an image.
Operaciones de API relacionadas
Si su aplicación requiere un alto grado de personalización, puede enviar solicitudes de API REST directamente. Debe escribir manualmente el código para calcular la firma. Para obtener más información sobre cómo calcular el encabezado de solicitud Authorization, consulte Signature V4 (recommended).
Puede procesar imágenes agregando el parámetro x-oss-process a la operación GetObject. Para obtener más información, consulte GetObject.
Ejemplo de procesamiento
GET /example.jpg?x-oss-process=image/codes HTTP/1.1
Host: image-demo.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 21 Jul 2023 08:56:50 GMT
Authorization: SignatureValue
Ejemplo de respuesta
HTTP/1.1 200 OK
Server: AliyunOSS
Date: Fri, 21 Jul 2023 08:56:52 GMT
Content-Type: application/json;charset=utf-8
Content-Length: 64
Connection: keep-alive
x-oss-request-id: 64BA48531253C5383707D5B3
ETag: "2CE2EA370531B7CC1D23BE6015CF5DA5"
Last-Modified: Mon, 10 Jul 2023 13:07:30 GMT
x-oss-object-type: Normal
x-oss-hash-crc64ecma: 13420962247653419692
x-oss-storage-class: Standard
x-oss-ec: 0048-00000104
Content-Disposition: attachment
x-oss-force-download: true
x-oss-server-time: 453
{
"RequestId" : "3B7BD09F-18D8-56F0-90B7-889FBD9FFF70",
"Codes": [
{
"Content": "https://www.aliyun.com/product/imm",
"Boundary": {
"Width": 741,
"Height": 706,
"Left": 460,
"Top": 295
}
}
]
}
Permisos
Una cuenta de Alibaba Cloud tiene permisos completos de forma predeterminada. Un usuario de Resource Access Management (RAM) o un rol de RAM no tiene permisos de forma predeterminada. Puede otorgar permisos a un usuario de RAM o a un rol de RAM mediante una RAM policy o un bucket policy.
-
Otorgue al usuario permisos para acceder a los recursos asociados.
-
Otorgue al usuario permisos para usar OSS en el procesamiento de datos.
API
Action
Descripción
GetObject
oss:GetObjectDescargar un objeto.
kms:DecryptEste permiso es obligatorio para descargar un objeto si los metadatos del objeto incluyen X-Oss-Server-Side-Encryption: KMS.
Ninguna
oss:ProcessImmPermiso para usar IMM en el procesamiento de datos a través de OSS.
PostProcessTask
oss:PostProcessTaskPermiso para usar funciones de procesamiento de datos mediante el envío de solicitudes POST, como en el procesamiento asíncrono (
x-oss-async-process). -
Otorgue al usuario permiso para usar la función de reconocimiento de códigos QR de IMM.
API
Action
Descripción
DetectImageCodes
imm:DetectImageCodesPermiso para usar IMM en el reconocimiento de códigos QR.
-
-
Otorgue al rol de servicio de IMM (el rol predeterminado es
AliyunIMMDefaultRoley su ARN esacs:ram:*:<account-id>:role/aliyunimmdefaultrole) permisos para acceder a los recursos asociados para el procesamiento de datos.API
Action
Descripción
GetObject
oss:GetObjectDescargar un objeto.
kms:DecryptEste permiso es obligatorio para descargar un objeto si los metadatos del objeto incluyen X-Oss-Server-Side-Encryption: KMS.
Facturación
El reconocimiento de códigos QR implica llamadas al servicio IMM, lo que genera cargos tanto para OSS como para IMM. Se generan los siguientes cargos:
-
OSS: Se aplican los siguientes conceptos facturables. Para obtener más información sobre los precios, consulte Precios de OSS:
API
Concepto facturable
Descripción
GetObject
Solicitudes GET
Se le cobran tarifas de solicitud según el número de solicitudes exitosas.
Tráfico saliente por Internet
Si llama a la operación GetObject mediante un endpoint público, como oss-cn-hangzhou.aliyuncs.com, o un endpoint de aceleración, como oss-accelerate.aliyuncs.com, se le cobran tarifas por tráfico saliente a través de Internet según el tamaño de los datos.
Recuperación de objetos IA
Si se recuperan objetos IA, se le cobran tarifas de recuperación de datos IA según el tamaño de los datos IA recuperados.
Recuperación de objetos Archive en un bucket con acceso en tiempo real habilitado
Si recupera objetos Archive en un bucket con acceso en tiempo real habilitado, se le cobran tarifas de recuperación de datos Archive según el tamaño de los objetos Archive recuperados.
Tarifas de aceleración de transferencia
Si habilita la aceleración de transferencia y utiliza un endpoint de aceleración para acceder a su bucket, se le cobran tarifas de aceleración de transferencia según el tamaño de los datos.
-
IMM: Se aplican los siguientes IMM billable items:
API
Concepto facturable
Descripción
DetectImageCodes
ImageQRCodes
Se le cobran tarifas de solicitud según el número de solicitudes exitosas.