Skip to content

Instantly share code, notes, and snippets.

@pvlasov
Last active November 4, 2019 22:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pvlasov/97332432aedaa071bc906efc6c864864 to your computer and use it in GitHub Desktop.
Save pvlasov/97332432aedaa071bc906efc6c864864 to your computer and use it in GitHub Desktop.
Shows how to use Zxing to write/read QR codes
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Base64;
import java.util.Random;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeWriter;
public class QrCodec {
public static void main(String[] args) throws Exception {
Random random = new Random();
byte[] data = new byte[(int) (1024*1.5)];
random.nextBytes(data);
String stringData = Base64.getEncoder().encodeToString(data);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(stringData, BarcodeFormat.QR_CODE, 370, 370);
File file = new File("qr.png");
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", file.toPath());
//--- Reading ---
BufferedImage bufferedImage = ImageIO.read(file);
LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result = new MultiFormatReader().decode(bitmap);
System.out.println(result.getText());
System.out.println(result.getText().equals(stringData));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment