java实现生成二维码技术发开工具类, 二更:带logo

具体的jar包就自行导入一下,这个小dome就是getUrl方法,传入内容,得到临时路径,至于得到file路径之后,

该oos就oos,该inputStream就走IO

package com.***.manage.util;

import java.awt.image.BufferedImage;
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 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;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public 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  String  getUrl(String  content){
		MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
		Map hints = new HashMap();
		//设置UTF-8, 防止中文乱码
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		//设置二维码四周白色区域的大小
		hints.put(EncodeHintType.MARGIN, 2);
		//设置二维码的容错性
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		//画二维码,记得调用multiFormatWriter.encode()时最后要带上hints参数,不然上面设置无效
		BitMatrix bitMatrix = null;
		File temp = null;
		try {
			bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400, hints);
			File directory = new File("");//设定为当前文件夹
			String path =directory.getCanonicalPath();//临时路径
			temp = File.createTempFile(path+"\\code", ".jpg");
			MatrixToImageWriter.writeToFile(bitMatrix, "jpg", temp);

		} catch (WriterException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return temp.getPath();
	}

}

 

 


上文的bug:

可以在本地跑,只是单纯的生成二维码,然后拿的的路径也是绝对路径

导致:无logo / 无法部署服务器jar包使用

优化版解决办法:使用内存流和相对路径

package com.****.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;

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;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.google.common.io.Resources.getResource;

public class MatrixToImageWriter {

	private static Logger logger = LoggerFactory.getLogger(MatrixToImageWriter.class);
	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  String  getUrl(String  content  ){
		MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
		Map hints = new HashMap();
		//设置UTF-8, 防止中文乱码
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		//设置二维码四周白色区域的大小
		hints.put(EncodeHintType.MARGIN, 1);
		//设置二维码的容错性
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		//画二维码,记得调用multiFormatWriter.encode()时最后要带上hints参数,不然上面设置无效
		BitMatrix bitMatrix = null;
		File temp = null;
		try {
			//图片大小280 * 280
			bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 280, 280, hints);
			//logo位置
			InputStream ins = MatrixToImageWriter.class.getResourceAsStream("/static/lib/images/logo.png");
			temp = new File( "QRCode.png");
			OutputStream os = new FileOutputStream(temp);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
			writeToFile(bitMatrix, "png", temp);
		} catch (WriterException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return temp.getPath();
	}
	/**
	 *
	 * @param matrix 二维码矩阵相关
	 * @param format 二维码图片格式
	 * @param file 二维码图片文件getContextPath("/lib/img/....jpg")
	 * @throws IOException
	 */
	public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
		BufferedImage image = toBufferedImage(matrix);
		Graphics2D gs = image.createGraphics();
		//根据二维码大小 计算logo的大小以及位置
		int ratioWidth = image.getWidth()*2/10;
		int ratioHeight = image.getHeight()*2/10;

		Image img = ImageIO.read(file);
		int logoWidth = img.getWidth(null)>ratioWidth?ratioWidth:img.getWidth(null);
		int logoHeight = img.getHeight(null)>ratioHeight?ratioHeight:img.getHeight(null);

		int x = (image.getWidth() - logoWidth) / 2;
		int y = (image.getHeight() - logoHeight) / 2;

		gs.drawImage(img, x, y, logoWidth, logoHeight, null);
		gs.dispose();
		img.flush();
		//将图片写出到指定位置(复制图片)
		OutputStream ops = new FileOutputStream(file);
		if(!ImageIO.write(image, format, ops)){
			throw new IOException("Could not write an image of format " + format + " to " + file);
		}
	}

}

调用使用:

 

String url = MatrixToImageWriter.getUrl(content);
File file=new File(url);
//上传二维码 到oss  略

 

你可能感兴趣的:(代码笔记,项目实战)