My linux world » Java – QRCode

Java - QRCode


Installation

If you use maven, add this to your pom.xml :

<dependencies>
(...)
 
  <dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>${zxing.version}</version>
  </dependency>
 
  <dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>${zxing.version}</version>
  </dependency>
 
(...)
</dependencies>

Encode

// Set parameters
String stringToEncode="Hello World!";
int imageWith=250;
int imageHeight=250;
String imageFormat="PNG";
File outputFile=new File("/tmp","myqrcode.png");
 
// Encode
Map<EncodeHintType, Object> hintMap = new EnumMap<>(EncodeHintType.class);
hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");		
 
BitMatrix bitMatrix = new QRCodeWriter().encode(stringToEncode, BarcodeFormat.QR_CODE, imageWith, imageHeight,hintMap);
MatrixToImageWriter.writeToPath(bitMatrix, imageFormat, outputFile.toPath());

Decode

// Parameters
File outputFile=new File("/tmp","myqrcode.png");
 
// Decode
BufferedImage image = ImageIO.read(outputFile);
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
 
EnumMap<DecodeHintType, ?> hints = new EnumMap<>(DecodeHintType.class);
QRCodeReader reader = new QRCodeReader();
Result result = reader.decode(bitmap, hints);
 
return result.getText();

Copyright © 2023 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.

Fork me on GitHub