All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.pentahohub.nexus.qrcode.QRCodeUtils Maven / Gradle / Ivy

package com.pentahohub.nexus.qrcode;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

public abstract class QRCodeUtils {
	private static final int BLACK = 0xFF000000;
	private static final int WHITE = 0xFFFFFFFF;
	private static final String FORMAT = "PNG";

	public static void write(String contents, int width, File out) throws IOException {
		BufferedImage image = writeToBufferedImage(contents, width);
		ImageIO.write(image, FORMAT, out);
	}

	public static void write(String contents, int width, OutputStream out) throws IOException {
		BufferedImage image = writeToBufferedImage(contents, width);
		ImageIO.write(image, FORMAT, out);
	}

	public static byte[] writeToByteArray(String contents, int width) throws IOException {
		ByteArrayOutputStream bao = new ByteArrayOutputStream();
		write(contents, width, bao);
		return bao.toByteArray();
	}

	public static void write(String contents, int width, ImageOutputStream out) throws IOException {
		BufferedImage image = writeToBufferedImage(contents, width);
		ImageIO.write(image, FORMAT, out);
	}

	private static BufferedImage writeToBufferedImage(String contents, int width) throws IOException {
		Map hints = new HashMap();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		BitMatrix bitMatrix;
		try {
			bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, width, hints);
		} catch (WriterException e) {
			throw new IOException(e);
		}
		BufferedImage image = writeToBufferedImage(bitMatrix);
		return image;
	}

	private static BufferedImage writeToBufferedImage(BitMatrix matrix) {
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
			}
		}
		return image;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy