java工具类——二维码

package www.zhidisoft.utils.zixing;

import java.awt.Graphics2D;  
import java.awt.image.BufferedImage;  
import java.io.File;  
import java.io.FileNotFoundException;
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.BinaryBitmap;  
import com.google.zxing.DecodeHintType;  
import com.google.zxing.EncodeHintType;  
import com.google.zxing.MultiFormatReader;  
import com.google.zxing.MultiFormatWriter;  
import com.google.zxing.NotFoundException;  
import com.google.zxing.Result;  
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;  
import com.google.zxing.client.j2se.MatrixToImageConfig;  
import com.google.zxing.client.j2se.MatrixToImageWriter;  
import com.google.zxing.common.BitMatrix;  
import com.google.zxing.common.HybridBinarizer;  
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;  
  
/** 
 * ZXing工具类 
 * @see ----------------------------------------------------------------------------------------------------------------------- 
 * @see 首页--https://code.google.com/p/zxing 
 * @see 介绍--用于解析多种格式条形码(EAN-13)和二维码(QRCode)的开源Java类库,其提供了多种应用的类库,如javase/jruby/cpp/csharp/android 
 * @see 说明--下载到的ZXing-2.2.zip是它的源码,我们在JavaSE中使用时需用到其core和javase两部分 
 * @see      可直接引入它俩的源码到项目中,或将它俩编译为jar再引入,这是我编译好的:http://download.csdn.net/detail/jadyer/6245849 
 * @see ----------------------------------------------------------------------------------------------------------------------- 
 * @see 经测试:用微信扫描GBK编码的中文二维码时出现乱码,用UTF-8编码时微信可正常识别 
 * @see       并且MultiFormatWriter.encode()时若传入hints参数来指定UTF-8编码中文时,微信压根就不识别所生成的二维码 
 * @see       所以这里使用的是这种方式new String(content.getBytes("UTF-8"), "ISO-8859-1") 
 * @see ----------------------------------------------------------------------------------------------------------------------- 
 * @see 将logo图片加入二维码中间时,需注意以下几点 
 * @see 1)生成二维码的纠错级别建议采用最高等级H,这样可以增加二维码的正确识别能力(我测试过,不设置级别时,二维码工具无法读取生成的二维码图片) 
 * @see 2)头像大小最好不要超过二维码本身大小的1/5,而且只能放在正中间部位,这是由于二维码本身结构造成的(你就把它理解成图片水印吧) 
 * @see 3)在仿照腾讯微信在二维码四周增加装饰框,那么一定要在装饰框和二维码之间留出白边,这是为了二维码可被识别 
 * @see ----------------------------------------------------------------------------------------------------------------------- 
 * @version v1.0 
 * @history v1.0-->方法新建,目前仅支持二维码的生成和解析,生成二维码时支持添加logo头像 
 * @editor Sep 10, 2013 9:32:23 PM 
 * @create Sep 10, 2013 2:08:16 PM 
 * @author 玄玉<http://blog.csdn.net/jadyer> 
 */  
public class ZixingCode {  
    private ZixingCode(){}  
      
    /** 
     * 为二维码图片增加logo头像 
     * @see 其原理类似于图片加水印 
     * @param imagePath 二维码图片存放路径(含文件名) 
     * @param logoPath  logo头像存放路径(含文件名) 
     */  
    private static void overlapImage(String imagePath, String logoPath) throws IOException {  
        BufferedImage image = ImageIO.read(new File(imagePath));  
        int logoWidth = image.getWidth()/5;   //设置logo图片宽度为二维码图片的五分之一  
        int logoHeight = image.getHeight()/5; //设置logo图片高度为二维码图片的五分之一  
        int logoX = (image.getWidth()-logoWidth)/2;   //设置logo图片的位置,这里令其居中  
        int logoY = (image.getHeight()-logoHeight)/2; //设置logo图片的位置,这里令其居中  
        Graphics2D graphics = image.createGraphics();  
        graphics.drawImage(ImageIO.read(new File(logoPath)), logoX, logoY, logoWidth, logoHeight, null);  
        graphics.dispose();  
        ImageIO.write(image, imagePath.substring(imagePath.lastIndexOf(".") + 1), new File(imagePath));  
    }  
  
      
    /** 
     * 生成二维码 
     * @param content   二维码内容 
     * @param charset   编码二维码内容时采用的字符集(传null时默认采用UTF-8编码) 
     * @param imagePath 二维码图片存放路径(含文件名) 
     * @param width     生成的二维码图片宽度 
     * @param height    生成的二维码图片高度 
     * @param logoPath  logo头像存放路径(含文件名,若不加logo则传null即可) 
     * @return 生成二维码结果(true or false) 
     */  
    public static boolean encodeQRCodeImage(String content, String charset, String imagePath, int width, int height, String logoPath) {  
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();  
        //指定编码格式  
        //hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");  
        //指定纠错级别(L--7%,M--15%,Q--25%,H--30%)  
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);  
        //编码内容,编码类型(这里指定为二维码),生成图片宽度,生成图片高度,设置参数  
        BitMatrix bitMatrix = null;  
        try {  
            bitMatrix = new MultiFormatWriter().encode(new String(content.getBytes(charset==null?"UTF-8":charset), "ISO-8859-1"), BarcodeFormat.QR_CODE, width, height, hints);  
        } catch (Exception e) {  
            System.out.println("编码待生成二维码图片的文本时发生异常,堆栈轨迹如下");  
            e.printStackTrace();  
            return false;  
        }  
        //生成的二维码图片默认背景为白色,前景为黑色,但是在加入logo图像后会导致logo也变为黑白色,至于是什么原因还没有仔细去读它的源码  
        //所以这里对其第一个参数黑色将ZXing默认的前景色0xFF000000稍微改了一下0xFF000001,最终效果也是白色背景黑色前景的二维码,且logo颜色保持原有不变  
        MatrixToImageConfig config = new MatrixToImageConfig(0xFF000001, 0xFFFFFFFF);  
        //这里要显式指定MatrixToImageConfig,否则还会按照默认处理将logo图像也变为黑白色(如果打算加logo的话,反之则不须传MatrixToImageConfig参数)  
        try {  
            MatrixToImageWriter.writeToFile(bitMatrix, imagePath.substring(imagePath.lastIndexOf(".") + 1), new File(imagePath), config);  
        } catch (IOException e) {  
            System.out.println("生成二维码图片[" + imagePath + "]时遇到异常,堆栈轨迹如下");  
            e.printStackTrace();  
            return false;  
        }  
        //此时二维码图片已经生成了,只不过没有logo头像,所以接下来根据传入的logoPath参数来决定是否加logo头像  
        if(null == logoPath){  
            return true;  
        }else{  
            //如果此时最终生成的二维码不是我们想要的,那么可以扩展MatrixToImageConfig类(反正ZXing提供了源码)  
            //扩展时可以重写其writeToFile方法,令其返回toBufferedImage()方法所生成的BufferedImage对象(尽管这种做法未必能解决为题,故需根据实际情景测试)  
            //然后替换这里overlapImage()里面的第一行BufferedImage image = ImageIO.read(new File(imagePath));  
            //即private static void overlapImage(BufferedImage image, String imagePath, String logoPath)  
            try {  
                //这里不需要判断logoPath是否指向了一个具体的文件,因为这种情景下overlapImage会抛IO异常  
                overlapImage(imagePath, logoPath);  
                return true;  
            } catch (IOException e) {  
                System.out.println("为二维码图片[" + imagePath + "]添加logo头像[" + logoPath + "]时遇到异常,堆栈轨迹如下");  
                e.printStackTrace();  
                return false;  
            }  
        }  
    }  
      
      
    /** 
     * 解析二维码 
     * @param imagePath 二维码图片存放路径(含文件名) 
     * @param charset   解码二维码内容时采用的字符集(传null时默认采用UTF-8编码) 
     * @return 解析成功后返回二维码文本,否则返回空字符串 
     */  
    public static String decodeQRCodeImage(String imagePath, String charset) {  
        BufferedImage image = null;  
        try {  
            image = ImageIO.read(new File(imagePath));  
        } catch (IOException e) {  
            e.printStackTrace();  
            return "";  
        }  
        if(null == image){  
            System.out.println("Could not decode QRCodeImage");  
            return "";  
        }  
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));  
        Map<DecodeHintType, String> hints = new HashMap<DecodeHintType, String>();  
        hints.put(DecodeHintType.CHARACTER_SET, charset==null ? "UTF-8" : charset);  
        Result result = null;  
        try {  
            result = new MultiFormatReader().decode(bitmap, hints);  
            return result.getText();  
        } catch (NotFoundException e) {  
            System.out.println("二维码图片[" + imagePath + "]解析失败,堆栈轨迹如下");  
            e.printStackTrace();  
            return "";  
        }  
    }
    
}  


测试类

	public static void main(String[] args) {
		String text ="二维码名片:\n姓名:王稀\nQQ:851372808"
				+ "\n电话:18995699027\n邮箱:qqicq2001@163.com\n博客:http://blog.csdn.net/qqicq2001";
		String imagePath ="C:/Users/lenovo/桌面/二维码.png";
		String logoPath = "C:/Users/lenovo/桌面/智递.png";
		ZixingCode.encodeQRCodeImage(text, null,imagePath, 800, 800,logoPath);
	}


当然,通常是用在项目中,也可以传入项目路径:

		String text ="二维码名片:\n姓名:王稀\nQQ:851372808"
				+ "\n电话:18995699027\n邮箱:qqicq2001@163.com\n博客:http://blog.csdn.net/qqicq2001";
		
		//项目路径:E:\apache-tomcat-7.0.42\webapps\web502\resources\code\二维码.png
		String filePath = request.getSession().getServletContext().getRealPath("/") + "resources/code/二维码.png";
		String logoPath = request.getSession().getServletContext().getRealPath("/") + "resources/code/智递.png";
		ZixingCode.encodeQRCodeImage(text, null,filePath, 800, 800,logoPath);


或者传给servlet:

@SuppressWarnings("serial")
@WebServlet(urlPatterns="/ZixingCodeServlet.do")
public class ZixingCodeServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String text ="二维码名片:\n姓名:王稀\nQQ:851372808"
				+ "\n电话:18995699027\n邮箱:qqicq2001@163.com\n博客:http://blog.csdn.net/qqicq2001";
		
		//项目路径:E:\apache-tomcat-7.0.42\webapps\web502\resources\code\二维码.png
		String filePath = request.getSession().getServletContext().getRealPath("/") + "resources/code/二维码.png";
		String logoPath = request.getSession().getServletContext().getRealPath("/") + "resources/code/智递.png";
		ZixingCode.encodeQRCodeImage(text, null,
				filePath, 800, 800,logoPath);
		BufferedImage image =ImageIO.read(new File(filePath));
		ImageIO.write(image, "JPEG", response.getOutputStream());
	}

}


这样,就可以在html或jsp中展示了

<img alt="" src="ZixingCodeServlet.do">


效果如下:



完整工具类可下载

http://download.csdn.net/detail/qqicq2001/9832432



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java生成二维码工具类的源码是一段用Java语言编写的程序代码,用于生成二维码图片。下面是一个简单的Java生成二维码工具类的源码示例: ```java import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import com.google.zxing.BarcodeFormat; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; public class QRCodeGenerator { public static void main(String[] args) { String text = "https://www.example.com"; // 要生成二维码的内容 int width = 300; // 二维码图片的宽度 int height = 300; // 二维码图片的高度 String format = "png"; // 二维码图片的格式 try { BufferedImage image = generateQRCode(text, width, height); saveImage(image, format, "qrcode.png"); System.out.println("二维码已生成。"); } catch (Exception e) { e.printStackTrace(); } } // 生成二维码图片 public static BufferedImage generateQRCode(String text, int width, int height) throws Exception { QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height); int matrixWidth = bitMatrix.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 (bitMatrix.get(i, j)) { graphics.fillRect(i, j, 1, 1); } } } return image; } // 保存二维码图片 public static void saveImage(BufferedImage image, String format, String filePath) throws IOException { ImageIO.write(image, format, new File(filePath)); } } ``` 这个工具类使用了Google的ZXing库来生成二维码。主要包含两个方法:`generateQRCode()`用于生成二维码图片,`saveImage()`用于保存二维码图片到文件。 使用时,只需要指定要生成二维码的内容、图片的宽度和高度,然后调用`generateQRCode()`方法获取生成的二维码图片,最后保存到文件即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值