Home > other >  How to convert image to qr code using java?
How to convert image to qr code using java?

Time:12-20

If we search image to qr code, there are many websites which converts image to qr code online.

But how can I do this in java?
I am using the following code for converting text to qr code:-

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class MyQr {

    public static void createQR(String data, String path,
                                String charset, Map hashMap,
                                int height, int width)
        throws WriterException, IOException
    {

        BitMatrix matrix = new MultiFormatWriter().encode(
            new String(data.getBytes(charset), charset),
            BarcodeFormat.QR_CODE, width, height);

        MatrixToImageWriter.writeToFile(
            matrix,
            path.substring(path.lastIndexOf('.')   1),
            new File(path));
    }

    public static void main(String[] args)
        throws WriterException, IOException,
            NotFoundException
    {

        String data = "TEXT IN QR CODE";

        String path = "image.png";
        String charset = "UTF-8";

        Map<EncodeHintType, ErrorCorrectionLevel> hashMap
            = new HashMap<EncodeHintType,
                        ErrorCorrectionLevel>();

        hashMap.put(EncodeHintType.ERROR_CORRECTION,
                    ErrorCorrectionLevel.L);

        createQR(data, path, charset, hashMap, 200, 200);
    }
}

But how to encode a image in qr code?

CodePudding user response:

I assume that you mean that you want to add an image (e.g. logo) to the QR Code.

This is generally done by overlaying a small image on top of the QR Code, usually in the center. QR Codes are still readable when a small portion is obscured, especially in the center.

You can use MatrixToImageWriter.toBufferedImage(matrix) to get a BufferedImage containing the QR Code image, and then use Java image methods to overlay the image. See, for example, overlay images in java

CodePudding user response:

Images are too big to be embedded into QR codes (with the exception of tiny icons). So instead, the image is put on a publicly accessible server and the URL of the image is embedded in the QR code.

Thus you need access to a server that can fulfill this. That's probably the bigger part of what you are about to implement.

Otherwise, it's straight-forward:

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class MyQr {

    /**
     * Uploads the image to a server and returns to image URL.
     * @param imagePath path to the image
     * @return image URL
     */
    public static URL uploadImage(String imagePath)
    {
        // implement a solution to put an image on a public server
        try {
            return new URL("https://yourserver/some_path/image.jpg");
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void createQR(String payloadImagePath, String qrCodeImagePath,
                                Map<EncodeHintType, ?> hints, int height, int width)
            throws WriterException, IOException
    {
        URL imageURL = uploadImage(payloadImagePath);

        BitMatrix matrix = new MultiFormatWriter().encode(
                imageURL.toString(), BarcodeFormat.QR_CODE, width, height, hints);

        String imageFormat = qrCodeImagePath.substring(qrCodeImagePath.lastIndexOf('.')   1);
        MatrixToImageWriter.writeToPath(matrix, imageFormat, Path.of(qrCodeImagePath));
    }

    public static void main(String[] args)
            throws WriterException, IOException
    {
        String payloadImagePath = "embed_this.jpg";
        String qrCodeImagePath = "qrcode.png";

        Map<EncodeHintType, ErrorCorrectionLevel> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);

        createQR(payloadImagePath, qrCodeImagePath, hints, 200, 200);
    }
}

BTW: The below code (from your code sample) is non-sense. At best, it creates a copy of the string, which is unnecessary. At worst, it corrupts all characters not supported by charset. I don't think you intended either one.

new String(data.getBytes(charset), charset)
  • Related