Java生成二维码的方法,QRCode、JQuery、Zxing
    		       		warning:
    		            这篇文章距离上次修改已过440天,其中的内容可能已经有所变动。
    		        
        		                
                在Java中生成二维码可以使用多种库,其中比较常用的有Google的Zxing和QRCode。以下是使用这两种库生成二维码的示例代码。
- 使用Zxing库生成二维码:
 
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
 
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
 
public class QRCodeGenerator {
    public static void main(String[] args) throws WriterException, IOException {
        String text = "Hello, World";
        int width = 200;
        int height = 200;
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
        Path path = FileSystems.getDefault().getPath("qrcode.png");
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
    }
}- 使用QRCode库生成二维码:
 
import com.swetake.util.Qrcode;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
 
public class QRCodeGenerator {
    public static void main(String[] args) throws IOException {
        String text = "Hello, World";
        Qrcode qrcode = new Qrcode();
        qrcode.setQrcodeErrorCorrect('M');
        qrcode.setQrcodeEncodeMode('B');
        qrcode.setQrcodeVersion(7);
        BufferedImage bufferedImage = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
        String[] content = {text};
        boolean[] skip = {false};
        byte[] d = qrcode.calQrcode(content, skip);
        byte[] p = qrcode.getQrcode(d);
        int pixOff = 0;
        int[] pix = bufferedImage.getRGB();
        for (int y = 0; y < 200; y++) {
            for (int x = 0; x < 200; x++) {
                pix[pixOff] = (p[pixOff] & 0xff) == 0 ? 0xFFFFFFFF : 0;
                pixOff++;
            }
        }
        bufferedImage.setRGB(0, 0, 200, 200, pix, 0, 200);
        ImageIO.write(bufferedImage, "png", new File("qrcode.png"));
    }
}在这两个示例中,我们都是生成了一个200x200像素的二维码图片,并将其保存为"qrcode.png"。你可以根据自己的需求修改文本内容和图片尺寸。
评论已关闭