java后台生成二维码

首先需要一个编译二维码的工具类,demo中提供两种方法,一种是将字符串转换成二维码,另一种是解析二维码转为 文字,很简单,看了大家就会了

/**
 * 将二维码解析为文字
 */
public class Decoder {
	public static void main(String[] args) {
		BufferedImage bufferedImage = null;
		try {
			bufferedImage = ImageIO.read(new File("z:/二维码文件.gif"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
		BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
		Hashtable hints = new Hashtable();
		hints.put(DecodeHintType.CHARACTER_SET, "GBK");
		Result result = null;
		try {
			result = new MultiFormatReader().decode(bitmap, hints);
		} catch (NotFoundException e) {
			e.printStackTrace();
		}
		System.out.println(result.toString());
	}
}
/**
 *将文字转换为二维码
 */
public class Encoder {
	public static void main(String[] args) throws Exception {
		String text = "你好龙哥哥";
		Hashtable hints = new Hashtable();
		// 内容所使用编码
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		BitMatrix bitMatrix = new MultiFormatWriter().encode(text,BarcodeFormat.QR_CODE, 300, 300, hints);
		// 生成二维码
		MatrixToImageWriter.writeToFile(bitMatrix, "gif", new File("z:/二维码文件.gif"));
		System.out.println("二维码生成完成");
	}
}
public final class MatrixToImageWriter {
	private static final int BLACK = 0xFF000000;
	private static final int WHITE = 0xFFFFFFFF;
	private MatrixToImageWriter() {
	}
	public static BufferedImage toBufferedImage(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;
	}
	public static void writeToFile(BitMatrix matrix, String format, File file)
			throws IOException {
		BufferedImage image = toBufferedImage(matrix);
		if (!ImageIO.write(image, format, file)) {
			throw new IOException("Could not write an image of format "
					+ format + " to " + file);
		}
	}
	public static void writeToStream(BitMatrix matrix, String format,
			OutputStream stream) throws IOException {
		BufferedImage image = toBufferedImage(matrix);
		if (!ImageIO.write(image, format, stream)) {
			throw new IOException("Could not write an image of format "
					+ format);
		}
	}
}

 

你可能感兴趣的:(Java基础篇)