All Products
Search
Document Center

Object Storage Service:QR code recognition

Last Updated:Aug 13, 2026

The QR code recognition feature detects multiple QR codes or barcodes in various images. It returns the bounding box and text content for each detected code. The system annotates the bounding box of each QR code or barcode and displays its text content in the output.

Overview

Intelligent Media Management (IMM) provides the QR code recognition feature that you can use to detect positions and content of one or more QR codes or barcodes from image files such as photos and screenshots and return the position information and text information that the codes convey. The position information contains the upper-left corner x-axis, upper-left corner y-axis, width, and height, as shown in the following figure.

  • QR code

    figqcode11

  • Barcode

    image

You can use the QR code recognition feature to implement QR code or barcode scanning and reading in your business applications. You can also develop features to block or pixelate QR codes or barcodes in images based on the QR code recognition feature.

Scenarios

  • Pay with QR codes: Payers can scan a QR code to complete payments.

  • Marketing and advertising with QR codes: Marketers and advertisers can add QR codes to posters and product packaging to promote products.

Usage notes

  • Only synchronous processing (x-oss-process) is supported.

  • A maximum of five QR codes can be detected in a single image.

  • Anonymous access will be denied.

How to use

Prerequisites

QR code recognition

Action: image/codes

Java

Use Java SDK 3.17.4 or later.

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

Use Python SDK 2.18.4 or later.

# -*- 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

Use Go SDK 3.0.2 or later.

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

Use PHP SDK 2.7.0 or later.

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

Parameters

Action: image/codes

Note

For more information about the response parameters, see DetectImageCodes - Detect QR codes in an image.

Related API operations

If your application requires a high degree of customization, you can send REST API requests directly. You must manually write code to calculate the signature. For more information about how to calculate the Authorization request header, see Signature V4 (recommended).

You can process images by adding the x-oss-process parameter to the GetObject operation. For more information, see GetObject.

Processing example

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

Response example

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
      }
    }
  ]
}

Permissions

An Alibaba Cloud account has full permissions by default. A Resource Access Management (RAM) user or RAM role has no permissions by default. You can grant permissions to a RAM user or RAM role using a RAM policy or a bucket policy.

  • Grant the user permissions to access the associated resources.

    • Grant the user permissions to use OSS for data processing.

      API

      Action

      Description

      GetObject

      oss:GetObject

      Download an object.

      kms:Decrypt

      This permission is required to download an object if the object metadata includes X-Oss-Server-Side-Encryption: KMS.

      None

      oss:ProcessImm

      The permission to use IMM for data processing through OSS.

      PostProcessTask

      oss:PostProcessTask

      The permission to use data processing features by sending POST requests, such as for asynchronous processing (x-oss-async-process).

    • Grant the user the permission to use the QR code recognition feature of IMM.

      API

      Action

      Description

      DetectImageCodes

      imm:DetectImageCodes

      The permission to use IMM for QR code recognition.

  • Grant the service role for IMM (the default role is AliyunIMMDefaultRole, and its ARN is acs:ram:*:<account-id>:role/aliyunimmdefaultrole) permissions to access the associated resources for data processing.

    API

    Action

    Description

    GetObject

    oss:GetObject

    Download an object.

    kms:Decrypt

    This permission is required to download an object if the object metadata includes X-Oss-Server-Side-Encryption: KMS.

Billing

Recognizing QR codes involves calls to the IMM service, which generates fees for both OSS and IMM. The following fees are generated:

  • OSS: The following billable items apply. For more information about pricing, see OSS Pricing:

    API

    Billable item

    Description

    GetObject

    GET requests

    You are charged request fees based on the number of successful requests.

    Outbound traffic over the Internet

    If you call the GetObject operation by using a public endpoint, such as oss-cn-hangzhou.aliyuncs.com, or an acceleration endpoint, such as oss-accelerate.aliyuncs.com, you are charged fees for outbound traffic over the Internet based on the data size.

    Retrieval of IA objects

    If IA objects are retrieved, you are charged IA data retrieval fees based on the size of the retrieved IA data.

    Retrieval of Archive objects in a bucket for which real-time access is enabled

    If you retrieve Archive objects in a bucket for which real-time access is enabled, you are charged Archive data retrieval fees based on the size of retrieved Archive objects.

    Transfer acceleration fees

    If you enable transfer acceleration and use an acceleration endpoint to access your bucket, you are charged transfer acceleration fees based on the data size.

  • IMM: The following IMM billable items apply:

    API

    Billable item

    Description

    DetectImageCodes

    ImageQRCodes

    You are charged request fees based on the number of successful requests.