简体   繁体   English

如何使用 java 将图像转换为二维码?

[英]How to convert image to qr code using java?

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?但是我怎么能在 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?但是如何在二维码中编码图像呢?

I assume that you mean that you want to add an image (eg logo) to the QR Code.我假设您的意思是要向 QR 码添加图像(例如徽标)。

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.可以使用MatrixToImageWriter.toBufferedImage(matrix)获取包含二维码图像的 BufferedImage,然后使用 Java 图像方法叠加图像。 See, for example, overlay images in java例如,参见java 中的叠加图像

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.因此,图像被放置在可公开访问的服务器上,图像的 URL 嵌入在二维码中。

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 .在最坏的情况下,它会破坏charset不支持的所有字符。 I don't think you intended either one.我不认为你打算任何一个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM