您的位置:首页 > 编程语言 > Java开发

一步一步教你用 java&n…

2016-01-21 10:20 218 查看
写的真好。。拜读原文地址:一步一步教你用 java 生成二维码作者:浪友dans


一步一步用 java 设计生成二维码

在物联网的时代,二维码是个很重要的东西了,现在无论什么东西都要搞个二维码标志,唯恐落伍,就差人没有用二维码识别了。也许有一天生分证或者户口本都会用二维码识别了。今天心血来潮,看见别人都为自己的博客添加了二维码,我也想搞一个测试一下.

 

主要用来实现两点:

1. 生成任意文字的二维码.

2. 在二维码的中间加入图像.

 

一、准备工作。

准备QR二维码3.0

版本的core包和一张jpg图片。





下载QR二维码包。

首先得下载
zxing.jar 包, 我这里用的是3.0
版本的core包

下载地址:
现在已经迁移到了github:
https://github.com/zxing/zxing/wiki/Getting-Started-Developing,

当然你也可以从maven仓库下载jar
包:
http://central.maven.org/maven2/com/google/zxing/core/









 

二、程序设计

 1、启动eclipse,新建一个java项目,命好项目名(本例取名为QRCodeSoft)。点下一步:

 



 

2、导入zxing.jar

包,
我这里用的是3.0

版本的core包:点“添加外部JAR(X)…”。









 





 

3、新建两个类,分别是:

BufferedImageLuminanceSource.java

QRCodeUtil.java



 

关键代码在于:BufferedImageLuminanceSource.java
和QRCodeUtil.java
, 其中测试的main
方法位于
QRCodeUtil.java 中。

BufferedImageLuminanceSource.java程序代码:

package qrcodesoft;

import java.awt.Graphics2D;

import java.awt.geom.AffineTransform;

import java.awt.image.BufferedImage;

import com.google.zxing.LuminanceSource;

public class BufferedImageLuminanceSource extends LuminanceSource
{

    private
final BufferedImage image;

    private
final int left;

    private
final int top;

    public
BufferedImageLuminanceSource(BufferedImage image) {

   
    this(image,
0, 0, image.getWidth(), image.getHeight());

    }

    public
BufferedImageLuminanceSource(BufferedImage image, int left,

   
   
    int top, int
width, int height) {

   
    super(width,
height);

   
    int
sourceWidth = image.getWidth();

   
    int
sourceHeight = image.getHeight();

   
    if (left +
width > sourceWidth || top + height > sourceHeight) {

   
   
    throw new
IllegalArgumentException(

   
   
   
   
    "Crop
rectangle does not fit within image data.");

   
    }

   
    for (int y =
top; y < top + height; y++) {

   
   
    for (int x =
left; x < left + width; x++) {

   
   
   
    if
((image.getRGB(x, y) & 0xFF000000) == 0) {

   
   
   
   
   
image.setRGB(x, y, 0xFFFFFFFF); // = white

   
   
   
    }

   
   
    }

   
    }

   
    this.image =
new BufferedImage(sourceWidth, sourceHeight,

   
   
   
   
BufferedImage.TYPE_BYTE_GRAY);

   
   
this.image.getGraphics().drawImage(image, 0, 0, null);

   
    this.left =
left;

   
    this.top =
top;

    }

   

    public
byte[] getRow(int y, byte[] row) {

   
    if (y < 0
|| y >= getHeight()) {

   
   
    throw new
IllegalArgumentException(

   
   
   
   
    "Requested
row is outside the image: " + y);

   
    }

   
    int width =
getWidth();

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: