Android生成带图片的二维码

一、问题描述

在开发中需要将信息转换为二维码存储并要求带有公司的logo,我们知道Google的Zxing开源项目就很好的帮助我们实现条形码、二维码的生成和解析,但带有logo的官网并没有提供demo,下面就通过实例看看如何实现以及Zxing的使用。

二、案例介绍
1、案例运行效果

2、案例准备工作

在项目中加入jar,只需加入core.jar

Zxing项目地址:https://github.com/zxing/zxing/

三、Zxing主要组件
1、BarcodeFormat

定义了不同的二进制编码方式,取值如下

EAN_13条形码,共计13位代码,比较常见,如商品上的包装上的都是这种条形码

CODE_QR二维码(矩阵码),比条形码存在更多信息,当下比较流行

CODE_128条形码 可表示可表示从 ASCII 0 到ASCII 127 共128个 字符 ,用于企业管理,生产流程控制

CODE_39条形码,编制简单只接受如下43个字符


2、MultiFormatWriter

主要包含一个 encode()方法,可实现产生编码(条形、二维码)

BitMatrix  encode(String contents, BarcodeFormat format, int width, int height, Hashtable hints)方法

参数 :

contents:要编码的内容

format:编码格式(条形、二维)

width,height:生成码的大小

hints:包含EncodeHintType(编码提示类型)信息的集合,主要设置字符编码,比如支持汉字的utf-8,如下:

Hashtable<EncodeHintType, String> hst = new Hashtable<EncodeHintType, String>();

hst.put(EncodeHintType.CHARACTER_SET, "UTF-8");

返回值 :BitMatrix 二维矩阵点

3、BitMatrix

BitMatrix :表现为一个二维矩阵,x表示列的位置,y表示行的位置,循序从左上角开始,一列一列排列(先x后y)

主要方法 :

getWidth():返回矩阵的宽度

getHeight():返回矩阵的高度

boolean get(x,y) :非常重要的方法,实现根据给定的x,y判断该位置是否有黑块

在产生二维码的应用中就是通过这个方法进行判断,然后把有黑块的点记录下来,使用Bitmap的setPixels()方法生成图形,详解案例的createCode()方法中的代码

四、完整代码

[Java] 查看源文件 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
public class MainActivity extends Activity {
  private EditText etCompany;
  private EditText etPhone;
  private EditText etEmail;
  private EditText etWeb;
  private Bitmap logo;
  private static final int IMAGE_HALFWIDTH = 40;//宽度值,影响中间图片大小
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //获得资源图片,可改成获取本地图片或拍照获取图片
    logo=BitmapFactory.decodeResource(super.getResources(),R.drawable.y014);
    etCompany =(EditText) findViewById(R.id.etCompany);
    etPhone=(EditText) findViewById(R.id.etPhone);
    etEmail =(EditText) findViewById(R.id.etEmail);
    etWeb =(EditText) findViewById(R.id.etWeb);
    findViewById(R.id.but).setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        // TODO Auto-generated method stub
        String company=etCompany.getText().toString().trim() ;
        String phone =etPhone .getText().toString().trim() ;
        String email = etEmail.getText().toString().trim() ;
        String web = etWeb.getText().toString().trim() ;
        //二维码中包含的文本信息
        String contents= "BEGIN:VCARD VERSION:3.0 ORG:"+company+" TEL:"+phone+" URL:"+web+" EMAIL:"+email+" END:VCARD";
      try {
        //调用方法createCode生成二维码
        Bitmap bm=createCode(contents,logo,BarcodeFormat.QR_CODE);
        ImageView img=(ImageView)findViewById(R.id.imgCode) ;
        //将二维码在界面中显示
        img.setImageBitmap(bm);
      } catch (WriterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      }
    });
  }
  /**
   * 生成二维码
   * @param string 二维码中包含的文本信息
   * @param mBitmap logo图片
   * @param format  编码格式
   * [url=home.php?mod=space&uid=309376]@return[/url] Bitmap 位图
   * @throws WriterException
   */
  public Bitmap createCode(String string,Bitmap mBitmap, BarcodeFormat format)
      throws WriterException {
    Matrix m = new Matrix();
    float sx = (float) 2 * IMAGE_HALFWIDTH / mBitmap.getWidth();
    float sy = (float) 2 * IMAGE_HALFWIDTH
        / mBitmap.getHeight();
    m.setScale(sx, sy);//设置缩放信息
    //将logo图片按martix设置的信息缩放
    mBitmap = Bitmap.createBitmap(mBitmap, 0, 0,
        mBitmap.getWidth(), mBitmap.getHeight(), m, false);
    MultiFormatWriter writer = new MultiFormatWriter();
    Hashtable<EncodeHintType, String> hst = new Hashtable<EncodeHintType, String>();
    hst.put(EncodeHintType.CHARACTER_SET, "UTF-8");//设置字符编码
    BitMatrix matrix = writer.encode(string, format, 400, 400, hst);//生成二维码矩阵信息
    int width = matrix.getWidth();//矩阵高度
    int height = matrix.getHeight();//矩阵宽度
    int halfW = width / 2;
    int halfH = height / 2;
    int[] pixels = new int[width * height];//定义数组长度为矩阵高度*矩阵宽度,用于记录矩阵中像素信息
    for (int y = 0; y < height; y++) {//从行开始迭代矩阵
      for (int x = 0; x < width; x++) {//迭代列
        if (x > halfW - IMAGE_HALFWIDTH && x < halfW + IMAGE_HALFWIDTH
            && y > halfH - IMAGE_HALFWIDTH
            && y < halfH + IMAGE_HALFWIDTH) {//该位置用于存放图片信息
//记录图片每个像素信息
          pixels[y * width + x] = mBitmap.getPixel(x - halfW
              + IMAGE_HALFWIDTH, y - halfH + IMAGE_HALFWIDTH);              } else {
          if (matrix.get(x, y)) {//如果有黑块点,记录信息
            pixels[y * width + x] = 0xff000000;//记录黑块信息
          }
        }
      }
    }
    Bitmap bitmap = Bitmap.createBitmap(width, height,
        Bitmap.Config.ARGB_8888);
    // 通过像素数组生成bitmap
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    return bitmap;
  }
}
原文地址:https://www.cnblogs.com/accumulater/p/6438143.html