SoFunction
Updated on 2025-03-10

How to get QR code from pictures on Android

I remember talking about scanning QR codes in my previous blog. Yesterday, the team leader asked me not only to scan and obtain QR codes, but also to obtain QR codes in them through pictures. For example, if someone takes a QR code photo and sends it to you, the app should be able to get the QR code of the picture.

I checked the information online and found that it was actually very simple. I can basically use the QRCodeReader to get the QR code in the ZXing jar package to get the picture QR code. However, I don’t understand most of the content myself. If you are interested, you can search for information by yourself.

1. After clicking the button, jump to the album, select the picture with the QR code, and return to the interface where the QR code is parsed. At this time, the path to the image is obtained through the returned URI.

 case CHOOSE_PIC:
          String[] proj = new String[]{};
          Cursor cursor = ().query((), proj, null, null, null);

          if(()){
            int columnIndex = ();
            (columnIndex);
            // Obtain the absolute path to get the QR code picture selected by the user            imgPath = (columnIndex);
          }
          ();

          //Get parsing results          Result ret = parseQRcodeBitmap(imgPath);
          if (ret==null){
            (,getString(.load_two_dimensional_error), Toast.LENGTH_LONG).show();
          }else {
// (,"Analysis result:" + (), Toast.LENGTH_LONG).show();            Intent intent = new Intent();
            (, ());
            (Activity.RESULT_OK, intent);
            (.fade_in, .fade_out);
            finish();
          }
          break;

This is to query the URI for URI, and then call parseQRcodeBitmap (imgPath) to get the QR code of the image.

2. Analyze the picture through the image path and obtain the QR code value of the picture.

//Analyze the QR code image, return the result encapsulated in the Result objectprivate  parseQRcodeBitmap(String bitmapPath){
  //Resolve conversion type UTF-8  Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
  (DecodeHintType.CHARACTER_SET, "utf-8");
  //Get the picture to be parsed   options = new ();
  //If we set inJustDecodeBounds to true, then (String path, Options opt)  //It will not really return a Bitmap for you, it will only retrieve its width and height for you.   = true;
  //The bitmap is null at this time. After this code, and is the width and height we want  Bitmap bitmap = (bitmapPath,options);
  //The side length of the picture we want to take out now (the QR code picture is square) is set to 400 pixels  /**
    = 400;
    = 400;
    = false;
   bitmap = (bitmapPath, options);
   */
  //The above practice limits bitmap to the size we want, but does not save memory. If we want to save memory, we still need to use the inSimpleSize property   =  / 400;
  if( <= 0){
     = 1; //Prevent its value from being less than or equal to 0  }
  /**
    * Auxiliary memory saving settings
    *
    * = .ARGB_4444; // The default is .ARGB_8888
    * = true;
    * = true;
    */
   = false;
  bitmap = (bitmapPath, options);
  // Create a new RGBLuminanceSource object and pass the bitmap image to this object  RGBLuminanceSource rgbLuminanceSource = new RGBLuminanceSource(bitmap);
  //Convert the picture to binary picture  BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(rgbLuminanceSource));
  //Initialize the parsing object  QRCodeReader reader = new QRCodeReader();
  //Start the analysis  Result result = null;
  try {
    result = (binaryBitmap, hints);
  } catch (Exception e) {
    // TODO: handle exception
  }

  return result;
}

Here, first obtain the bitmap of the image. You need to make the bitmap of the obtained bitmap unique to a certain size, and then implement it through

// Create a new RGBLuminanceSource object and pass the bitmap image to this objectRGBLuminanceSource rgbLuminanceSource = new RGBLuminanceSource(bitmap);
//Convert the picture to binary pictureBinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(rgbLuminanceSource));
//Initialize the parsing objectQRCodeReader reader = new QRCodeReader();

Convert the QR code of bitmap into a picture, then convert the picture into a binary picture, call the result = (binaryBitmap, hints); code converts the binary picture into a QR code, and then directly obtains the string that returns the value as the QR code value.

A custom class RGBLuminanceSource is used, and the main function is to obtain the QR code content of the picture and filter the contents of the QR code to facilitate the next parsing of the QR code.

package .;
import ;

import ;
import ;

import ;

public class RGBLuminanceSource extends LuminanceSource {
  private final byte[] luminances;

  public RGBLuminanceSource(Bitmap bitmap) {
    super((), ());
    //Get the width and height of the picture    int width = ();
    int height = ();
    //Get the pixels of the image    int[] pixels = new int[width * height];
    //
    (pixels, 0, width, 0, 0, width, height);
    //In order to measure the pure decoding speed, we will front the entire image grayscale array, which is the same channel    // YUVLuminanceSource is used in real life.    //Get the number of bytes of pixel size    luminances = new byte[width * height];
    //Get the pixel color per point of the picture    for (int y = 0; y < height; y++) {
      int offset = y * width;
      for (int x = 0; x < width; x++) {
        int pixel = pixels[offset + x];
        int r = (pixel >> 16) & 0xff;
        int g = (pixel >> 8) & 0xff;
        int b = pixel & 0xff;
        //When the three color values ​​of a certain point are the same, the corresponding byte corresponding space is assigned to its value        if (r == g && g == b) {
          luminances[offset + x] = (byte) r;
        }
        //In other cases, the corresponding assignment of byte space is:        else {
          luminances[offset + x] = (byte) ((r + g + g + b) >> 2);
        }
      }
    }
  }

  public RGBLuminanceSource(String path) throws FileNotFoundException {
    this(loadBitmap(path));
  }


  @Override
  public byte[] getMatrix() {
    return luminances;
  }

  @Override
  public byte[] getRow(int arg0, byte[] arg1) {
    if (arg0 < 0 || arg0 >= getHeight()) {
      throw new IllegalArgumentException(
          "Requested row is outside the image: " + arg0);
    }
    int width = getWidth();
    if (arg1 == null ||  < width) {
      arg1 = new byte[width];
    }
    (luminances, arg0 * width, arg1, 0, width);
    return arg1;
  }

  private static Bitmap loadBitmap(String path) throws FileNotFoundException {
    Bitmap bitmap = (path);
    if (bitmap == null) {
      throw new FileNotFoundException("Couldn't open " + path);
    }
    return bitmap;
  }
}

This way you can identify the QR code of the picture. You must first import the ZXing jar package with this function. This is very simple. There are many introductions on the Internet. You can search for it yourself.

Android gets the QR code from the picture and finishes it.

It's that simple.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.