二维码后台生成方法

二维码后台生成方法
1.下载包:http://mvnrepository.com/artifact/com.google.zxing/core/3.1.0
core-3.1.0.jar
log4j-1.2.14.jar
或者在pom.xml增加:
        <!-- log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.14</version>
        </dependency>

<!-- 二维码 -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.1.0</version>
        </dependency>

2.页面写法:
<div class="thumbnail">
    <img alt="这是二维码" src="<%=basePath%>utils/qrcode?content=http://www.baidu.com&width=200&height=200" />
</div>
3.control写法:
private ModelAndView createQrCode(String content, int width, int height,
            HttpServletResponse response) {
        BufferedImage bi = QrCodeUtils.encodePRToBufferedImage(content, width,
                height);
        try {
            response.setContentType("image/jpeg");
            OutputStream os = response.getOutputStream();
            ImageIO.write(bi, "jpg", os);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.sendError(500);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return null;
    }

package com.taopl.test;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
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;

public class QrCodeUtils {
    
    private static Logger logger = Logger.getLogger(QrCodeUtils.class);
    
    // 图片宽度的一般
    private static final int IMAGE_WIDTH = 80;
    private static final int IMAGE_HEIGHT = 80;
    private static final int IMAGE_HALF_WIDTH = IMAGE_WIDTH / 2;
    private static final int FRAME_WIDTH = 2;

/**
     * 生成普通二维码
     *
     * @param contents
     * @param width
     * @param height
     * @param imgPath
     */
    public static void encodePR(String contents, int width, int height, String imgPath) {
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        // 指定纠错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        // 指定编码格式
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
                    BarcodeFormat.QR_CODE, width, height, hints);
            
            MatrixToImageWriter.writeToStream(bitMatrix, "jpg",
                    new FileOutputStream(imgPath));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 生成普通二维码
     *
     * @param contents
     * @param width
     * @param height
     * @param imgPath
     */
    public static String generatorPR(String contents, String width, String height,String imgPath) {
        String fileName=CommonUtils.getCurTimestamp()+".jpg";
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        // 指定纠错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        // 指定编码格式
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        try {
            if(CommonUtils.isEmpty(width)){
                width="100";
            }
            if(CommonUtils.isEmpty(height)){
                height="100";
            }
            
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
                    BarcodeFormat.QR_CODE, Integer.valueOf(width), Integer.valueOf(height), hints);
            
            MatrixToImageWriter.writeToStream(bitMatrix, "jpg",
                    new FileOutputStream(imgPath+"/"+fileName));
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }
    
    
    
    /**
     * 生成普通二维码
     *
     * @param contents
     * @param width
     * @param height
     */
    public static BufferedImage encodePRToBufferedImage(String contents, int width, int height) {
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        // 指定纠错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        // 指定编码格式
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        try {
            if(width<=0){
                width=100;
            }
            if(height<=0){
                height=100;
            }
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
                    BarcodeFormat.QR_CODE, width, height, hints);
            
            return MatrixToImageWriter.toBufferedImage(bitMatrix);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

/**
     * 生成带图片的二维码
     *
     * @param content
     * @param width
     * @param height
     * @param srcImagePath
     * @param destImagePath
     */
    public static void encodePR(String content, int width, int height,
            String srcImagePath, String destImagePath) {
        try {
            ImageIO.write(genBarcode(content, width, height, srcImagePath),
                    "jpg", new File(destImagePath));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }

/**
     * 针对二维码进行解析
     *
     * @param imgPath
     * @return
     */
    public static String decodePR(String imgPath) {
        BufferedImage image = null;
        Result result = null;
        try {
            image = ImageIO.read(new File(imgPath));
            if (image == null) {
                logger.error("the decode image may be not exists.");
            }
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            hints.put(DecodeHintType.CHARACTER_SET, "GBK");

result = new MultiFormatReader().decode(bitmap, hints);
            return result.getText();

} catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

/**
     * 创建条形码
     *
     * @param contents
     * @param width
     * @param height
     * @param imgPath
     */
    public static void encodeBar(String contents, int width, int height, String imgPath) {
        // 条形码的最小宽度
        int codeWidth = 98;
        codeWidth = Math.max(codeWidth, width);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
                    BarcodeFormat.EAN_13, codeWidth, height, null);

MatrixToImageWriter.writeToStream(bitMatrix, "png",
                    new FileOutputStream(imgPath));

} catch (Exception e) {
            e.printStackTrace();
        }
    }

/**
     * 针对条形码进行解析
     *
     * @param imgPath
     * @return
     */
    public static String decodeBar(String imgPath) {
        BufferedImage image = null;
        Result result = null;
        try {
            image = ImageIO.read(new File(imgPath));
            if (image == null) {
                logger.error("the decode image may be not exit.");
            }
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

result = new MultiFormatReader().decode(bitmap, null);
            return result.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

/**
     * 把传入的原始图像按高度和宽度进行缩放,生成符合要求的图标
     *
     * @param srcImageFile 源文件地址
     * @param height 目标高度
     * @param width 目标宽度
     * @param hasFiller 比例不对时是否需要补白:true为补白; false为不补白;
     * @throws IOException
     */
    private static BufferedImage scale(String srcImageFile, int height, int width,
            boolean hasFiller) throws IOException {
        double ratio = 0.0; // 缩放比例
        File file = new File(srcImageFile);
        BufferedImage srcImage = ImageIO.read(file);
        Image destImage = srcImage.getScaledInstance(width, height,
                BufferedImage.SCALE_SMOOTH);
        // 计算比例
        if ((srcImage.getHeight() > height) || (srcImage.getWidth() > width)) {
            if (srcImage.getHeight() > srcImage.getWidth()) {
                ratio = (new Integer(height)).doubleValue()
                        / srcImage.getHeight();
            } else {
                ratio = (new Integer(width)).doubleValue()
                        / srcImage.getWidth();
            }
            AffineTransformOp op = new AffineTransformOp(
                    AffineTransform.getScaleInstance(ratio, ratio), null);
            destImage = op.filter(srcImage, null);
        }
        if (hasFiller) {// 补白
            BufferedImage image = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D graphic = image.createGraphics();
            graphic.setColor(Color.white);
            graphic.fillRect(0, 0, width, height);
            if (width == destImage.getWidth(null))
                graphic.drawImage(destImage, 0,
                        (height - destImage.getHeight(null)) / 2,
                        destImage.getWidth(null), destImage.getHeight(null),
                        Color.white, null);
            else
                graphic.drawImage(destImage,
                        (width - destImage.getWidth(null)) / 2, 0,
                        destImage.getWidth(null), destImage.getHeight(null),
                        Color.white, null);
            graphic.dispose();
            destImage = image;
        }
        return (BufferedImage) destImage;
    }

/**
     * 产生带有图片的二维码缓冲图像
     * @param content
     * @param width
     * @param height
     * @param srcImagePath
     * @return
     * @throws WriterException
     * @throws IOException
     */
    private static BufferedImage genBarcode(String content, int width, int height,
            String srcImagePath) throws WriterException, IOException {
        // 读取源图像
        BufferedImage scaleImage = scale(srcImagePath, IMAGE_WIDTH,
                IMAGE_HEIGHT, true);
        int[][] srcPixels = new int[IMAGE_WIDTH][IMAGE_HEIGHT];
        for (int i = 0; i < scaleImage.getWidth(); i++) {
            for (int j = 0; j < scaleImage.getHeight(); j++) {
                srcPixels[i][j] = scaleImage.getRGB(i, j);
            }
        }

Map<EncodeHintType, Object> hint = new HashMap<EncodeHintType, Object>();
        hint.put(EncodeHintType.CHARACTER_SET, "GBK");
        hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 生成二维码
        MultiFormatWriter mutiWriter = new MultiFormatWriter();
        BitMatrix matrix = mutiWriter.encode(content, BarcodeFormat.QR_CODE,
                width, height, hint);

// 二维矩阵转为一维像素数组
        int halfW = matrix.getWidth() / 2;
        int halfH = matrix.getHeight() / 2;
        int[] pixels = new int[width * height];

for (int y = 0; y < matrix.getHeight(); y++) {
            for (int x = 0; x < matrix.getWidth(); x++) {
                // 读取图片
                if (x > halfW - IMAGE_HALF_WIDTH
                        && x < halfW + IMAGE_HALF_WIDTH
                        && y > halfH - IMAGE_HALF_WIDTH
                        && y < halfH + IMAGE_HALF_WIDTH) {
                    pixels[y * width + x] = srcPixels[x - halfW
                            + IMAGE_HALF_WIDTH][y - halfH + IMAGE_HALF_WIDTH];
                }
                // 在图片四周形成边框
                else if ((x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
                        && x < halfW - IMAGE_HALF_WIDTH + FRAME_WIDTH
                        && y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH
                        + IMAGE_HALF_WIDTH + FRAME_WIDTH)
                        || (x > halfW + IMAGE_HALF_WIDTH - FRAME_WIDTH
                                && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
                                && y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH
                                + IMAGE_HALF_WIDTH + FRAME_WIDTH)
                        || (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
                                && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
                                && y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH
                                - IMAGE_HALF_WIDTH + FRAME_WIDTH)
                        || (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH
                                && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
                                && y > halfH + IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH
                                + IMAGE_HALF_WIDTH + FRAME_WIDTH)) {
                    pixels[y * width + x] = 0xfffffff;
                } else {
                    // 此处可以修改二维码的颜色,可以分别制定二维码和背景的颜色;
                    pixels[y * width + x] = matrix.get(x, y) ? 0xff000000
                            : 0xfffffff;
                }
            }
        }

BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        image.getRaster().setDataElements(0, 0, width, height, pixels);

return image;
    }
    
    public static void main(String[] args) {
        String contents = "http://www.google.com";
        String imgPath = "d:\\test";
        generatorPR(contents, "100", "100",imgPath);
    }

}

时间: 2024-08-29 13:34:32

二维码后台生成方法的相关文章

IOS使用ZBarSDK实现二维码的生成和扫描

现在二维码的使用也是越来越多,那我们在做APP的时候,有时也需要考虑二维码的生成和扫描 首先简单的讲一下二维码的生成 首先定义一个ImageView来显示生成的二维码图片 只是简单的做一下字符串转化成二维码 导入 libqrencode文件 引入头文件#import "QRCodeGenerator.h" 即可使用 imageview.image = [QRCodeGenerator qrImageForString:@"www.cnblogs.com/myselfxiaox

iOS开发 - 二维码的生成与读取

二维码的生成 从iOS7開始集成了二维码的生成和读取功能 此前被广泛使用的zbarsdk眼下不支持64位处理器 生成二维码的步骤: 导入CoreImage框架 通过滤镜CIFilter生成二维码 二维码的内容(传统的条形码仅仅能放数字): 纯文本 名片 URL 生成二维码 // 1. 实例化二维码滤镜 CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"]; // 2. 恢复滤镜的默认属性 [filter se

Android实例-实现扫描二维码并生成二维码(XE8+小米5)

相关资料: 第三方资料太大没法写在博文上,请下载CSDN的程序包. 程序包下载: 过几天,刚上传的包,都没有办法显示. 注意事项: 如果只加了Lib,然没有改AndroidManifest.xml,App在呼叫BarCode时会ANR没反应.开始可能没有官方的classes.dex,但如果发现编译出错后,请再检查一下.TMessageManager须加System.Messaging单元. 使用DelphiXE7加入JavaLibrary后,呼叫Zxing相机1.新建一个DelphiXE工程,双

ios-深度解析二维码的生成与使用

利用一个小demo来对二维码进行学习,总共四个界面(主界面,生成二维码界面,识别二维码界面,扫描二维码界面) 一.二维码的介绍 1.什么是二维码? 二维条码/二维码是用某种特定的几何图形按一定规律在平面分布的黑白相间的图形记录数据符号信息的 总结: 用图形记录标记一些信息,方便通过图形识别来获取信息 2 应用场景 信息获取(名片.地图.WIFI密码.资料) 手机电商(用户扫码.手机直接购物下单) 手机支付(扫描商品二维码,通过银行或第三方支付提供的手机端通道完成支付) 微信添加好友 二.二维码界

iOS二维码的生成与扫描

由于近期工作中遇到了个需求:需要将一些固定的字段 在多个移动端进行相互传输,所以就想到了 二维码 这个神奇的东东! 现在的大街上.连个摊煎饼的大妈 都有自己的二维码来让大家进行扫码支付.可见现在的二维码使用率多高, 不光如此,在很多的社交类的APP 基本都有扫一扫加好友这个功能吧,因此决定学一学这个神奇的东西. 查找了一些资料博客啊发现,iOS7之前 对于开发人员来说 熟悉的第三方QRCode库有: ZXingGoogle出品并开源 一直到现在都还有专人维护 是世界上使用最广的二维码库 iOS上

Android 基于google Zxing实现二维码的生成,识别和长按识别的效果

最近项目用到了二维码的生成与识别,之前没有接触这块,然后就上网搜了搜,发现有好多这方面的资源,特别是google Zxing对二维码的封装,实现的已经不错了,可以直接拿过来引用,下载了他们的源码后,只做了少少的改动,就是在Demo中增加了长按识别的功能,网上虽然也有长按识别的Demo,但好多下载下来却无法运行,然后总结了一下,加在了下面的Demo中. 如图所示,引用时直接把用红色圈起来的包放在你项目所对应的文件夹下,当然一些资源文件,比如string.xml里项目的引用你自己添加上就是 当然别忘

Android二维码的生成算法原理简介

二维码的定义:二维码 (2-dimensional bar code),是用某种特定的几何图形按一定规律在平面(二维方向上)分布的黑白相间的图形记录数据符号信息的.在许多种类的二维条码中,常用的码制有:Data Matrix, Maxi Code, Aztec, QR Code, Vericode, PDF417, Ultracode, Code 49, Code 16K等.1.堆叠式/行排式二维条码,如,Code 16K.Code 49.PDF417(如下图)等2.矩阵式二维码,最流行莫过于Q

java实现二维码的生成与解析

二维码的生成及解析的低层实现并不简单,我们只需要知道怎么使用就可以了,参考博客:https://blog.csdn.net/jam_fanatic/article/details/82818857 1.maven中jar包引用com.google.zxing: 2.创建QRCodeUtil二维码工具类,使用谷歌提供的帮助类BufferedImageLuminanceSource绘制二维码. 生成二维码:QRCodeUtil.encode(编码到二维码中的内容, 嵌入二维码的图片路径, 生成的二维

Android zxing 解析二维码,生成二维码极简demo

zxing 官方的代码很多,看起来很费劲,此demo只抽取了有用的部分,实现了相机预览解码,解析本地二维码,生成二维码三个功能. 简化后的结构如下: 废话少说直接上代码: BaseDecodeHandler: package com.song.zxing.decode; import android.graphics.Bitmap; import android.os.Bundle; import com.google.zxing.BarcodeFormat; import com.google