QR-Codes für Termine mit Java erzeugenSeptember 2016
Mit dem Projekt
ZXing ("Zebra Crossing") ist das Erzeugen von Barcodes aus Java sehr einfach.
Auf der ZXing-Seite gibt es eine
Liste mit möglichen Barcode-Inhalten. Dort ist ersichtlich, dass Termine über das iCal-Format übertragen werden können, z.B.:
BEGIN:VEVENT
SUMMARY:Test Meeting
DTSTART:20080811T190000Z
DTEND:20080811T200000Z
END:VEVENT
Das folgende Beispiel ist von
crunchify.com übernommen und wurde auf den Anwendungsfall mit Terminen modifiziert. Für ein übergebenes Datum und ein Betreff wird ein QR-Code mit Termin im iCal-Format erzeugt.
package util;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.EnumMap;
import java.util.Map;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public final class QRCodeGenerator {
public static BufferedImage getQRImageFor(String summary, Date startDate, Date endDate) throws WriterException {
DateFormat df = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
String myCodeText = "BEGIN:VEVENT\n"
+"SUMMARY:"+summary.replace('\n', ' ')+"\n"
+"DTSTART:"+df.format(startDate)+"\n"
+"DTEND:"+df.format(endDate)+"\nEND:VEVENT";
int size = 250;
Map<EncodeHintType, Object> hintMap = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
// Now with zxing version 3.2.1 you could change border size (white
// border size to just 1)
hintMap.put(EncodeHintType.MARGIN, 1); /* default = 4 */
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix byteMatrix = qrCodeWriter.encode(myCodeText, BarcodeFormat.QR_CODE, size, size, hintMap);
int matrixWidth = byteMatrix.getWidth();
BufferedImage image = new BufferedImage(matrixWidth, matrixWidth, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, matrixWidth, matrixWidth);
graphics.setColor(Color.BLACK);
for (int i = 0; i < matrixWidth; i++) {
for (int j = 0; j < matrixWidth; j++) {
if (byteMatrix.get(i, j)) {
graphics.fillRect(i, j, 1, 1);
}
}
}
return image;
}
}