首页 > 代码库 > Android二维码之创建

Android二维码之创建

技术分享

1.Android 有自带的jar包可以生成二维码core-3.0.0.jar,其中的com.google.zxing包

2.写一个二维码生成的工具类,网上搜的话应该一大堆。

技术分享
  1 package com.example.administrator.twocodedemo;
  2 
  3 import android.content.Context;
  4 import android.graphics.Bitmap;
  5 import android.graphics.Bitmap.Config;
  6 import android.graphics.Canvas;
  7 import android.graphics.Color;
  8 import android.graphics.PointF;
  9 import android.view.Gravity;
 10 import android.view.View.MeasureSpec;
 11 import android.widget.LinearLayout;
 12 import android.widget.LinearLayout.LayoutParams;
 13 import android.widget.TextView;
 14 
 15 import com.google.zxing.BarcodeFormat;
 16 import com.google.zxing.EncodeHintType;
 17 import com.google.zxing.MultiFormatWriter;
 18 import com.google.zxing.WriterException;
 19 import com.google.zxing.common.BitMatrix;
 20 import com.google.zxing.qrcode.QRCodeWriter;
 21 
 22 import java.util.Hashtable;
 23 
 24 /** 
 25 *
 26 *     生成条形码和二维码的工具
 27 */
 28 public class ZXingUtils {
 29     /**
 30      * 生成二维码 要转换的地址或字符串,可以是中文
 31      * 
 32      * @param url
 33      * @param width
 34      * @param height
 35      * @return
 36      */
 37     public static Bitmap createQRImage(String url, final int width, final int height) {
 38         try {
 39             // 判断URL合法性
 40             if (url == null || "".equals(url) || url.length() < 1) {
 41                 return null;
 42             }
 43             Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
 44             hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
 45             // 图像数据转换,使用了矩阵转换
 46             BitMatrix bitMatrix = new QRCodeWriter().encode(url,
 47                     BarcodeFormat.QR_CODE, width, height, hints);
 48             int[] pixels = new int[width * height];
 49             // 下面这里按照二维码的算法,逐个生成二维码的图片,
 50             // 两个for循环是图片横列扫描的结果
 51             for (int y = 0; y < height; y++) {
 52                 for (int x = 0; x < width; x++) {
 53                     if (bitMatrix.get(x, y)) {
 54                         pixels[y * width + x] = 0xff000000;
 55                     } else {
 56                         pixels[y * width + x] = 0xffffffff;
 57                     }
 58                 }
 59             }
 60             // 生成二维码图片的格式,使用ARGB_8888
 61             Bitmap bitmap = Bitmap.createBitmap(width, height,
 62                     Bitmap.Config.ARGB_8888);
 63             bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
 64             return bitmap;
 65         } catch (WriterException e) {
 66             e.printStackTrace();
 67         }
 68         return null;
 69     }
 70 
 71     /**
 72      * 生成条形码
 73      *
 74      * @param context
 75      * @param contents
 76      *            需要生成的内容
 77      * @param desiredWidth
 78      *            生成条形码的宽带
 79      * @param desiredHeight
 80      *            生成条形码的高度
 81      * @param displayCode
 82      *            是否在条形码下方显示内容
 83      * @return
 84      */
 85     public static Bitmap creatBarcode(Context context, String contents,
 86                                       int desiredWidth, int desiredHeight, boolean displayCode) {
 87         Bitmap ruseltBitmap = null;
 88         /**
 89          * 图片两端所保留的空白的宽度
 90          */
 91         int marginW = 20;
 92         /**
 93          * 条形码的编码类型
 94          */
 95         BarcodeFormat barcodeFormat = BarcodeFormat.CODE_128;
 96 
 97         if (displayCode) {
 98             Bitmap barcodeBitmap = encodeAsBitmap(contents, barcodeFormat,
 99                     desiredWidth, desiredHeight);
100             Bitmap codeBitmap = creatCodeBitmap(contents, desiredWidth + 2
101                     * marginW, desiredHeight, context);
102             ruseltBitmap = mixtureBitmap(barcodeBitmap, codeBitmap, new PointF(
103                     0, desiredHeight));
104         } else {
105             ruseltBitmap = encodeAsBitmap(contents, barcodeFormat,
106                     desiredWidth, desiredHeight);
107         }
108 
109         return ruseltBitmap;
110     }
111 
112     /**
113      * 生成条形码的Bitmap
114      *
115      * @param contents
116      *            需要生成的内容
117      * @param format
118      *            编码格式
119      * @param desiredWidth
120      * @param desiredHeight
121      * @return
122      * @throws WriterException
123      */
124     protected static Bitmap encodeAsBitmap(String contents,
125                                            BarcodeFormat format, int desiredWidth, int desiredHeight) {
126         final int WHITE = 0xFFFFFFFF;
127         final int BLACK = 0xFF000000;
128 
129         MultiFormatWriter writer = new MultiFormatWriter();
130         BitMatrix result = null;
131         try {
132             result = writer.encode(contents, format, desiredWidth,
133                     desiredHeight, null);
134         } catch (WriterException e) {
135             // TODO Auto-generated catch block
136             e.printStackTrace();
137         }
138 
139         int width = result.getWidth();
140         int height = result.getHeight();
141         int[] pixels = new int[width * height];
142         // All are 0, or black, by default
143         for (int y = 0; y < height; y++) {
144             int offset = y * width;
145             for (int x = 0; x < width; x++) {
146                 pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
147             }
148         }
149 
150         Bitmap bitmap = Bitmap.createBitmap(width, height,
151                 Bitmap.Config.ARGB_8888);
152         bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
153         return bitmap;
154     }
155 
156     /**
157      * 生成显示编码的Bitmap
158      *
159      * @param contents
160      * @param width
161      * @param height
162      * @param context
163      * @return
164      */
165     protected static Bitmap creatCodeBitmap(String contents, int width,
166                                             int height, Context context) {
167         TextView tv = new TextView(context);
168         LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
169                 LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
170         tv.setLayoutParams(layoutParams);
171         tv.setText(contents);
172         tv.setHeight(height);
173         tv.setGravity(Gravity.CENTER_HORIZONTAL);
174         tv.setWidth(width);
175         tv.setDrawingCacheEnabled(true);
176         tv.setTextColor(Color.BLACK);
177         tv.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
178                 MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
179         tv.layout(0, 0, tv.getMeasuredWidth(), tv.getMeasuredHeight());
180 
181         tv.buildDrawingCache();
182         Bitmap bitmapCode = tv.getDrawingCache();
183         return bitmapCode;
184     }
185 
186     /**
187      * 将两个Bitmap合并成一个
188      * 
189      * @param first
190      * @param second
191      * @param fromPoint
192      *            第二个Bitmap开始绘制的起始位置(相对于第一个Bitmap)
193      * @return
194      */
195     protected static Bitmap mixtureBitmap(Bitmap first, Bitmap second,
196                                           PointF fromPoint) {
197         if (first == null || second == null || fromPoint == null) {
198             return null;
199         }
200         int marginW = 20;
201         Bitmap newBitmap = Bitmap.createBitmap(
202                 first.getWidth() + second.getWidth() + marginW,
203                 first.getHeight() + second.getHeight(), Config.ARGB_4444);
204         Canvas cv = new Canvas(newBitmap);
205         cv.drawBitmap(first, marginW, 0, null);
206         cv.drawBitmap(second, fromPoint.x, fromPoint.y, null);
207         cv.save(Canvas.ALL_SAVE_FLAG);
208         cv.restore();
209 
210         return newBitmap;
211     }
212 
213 }
ZXingUtils

3.MainActivity

@OnClick({R.id.btn_create, R.id.iv_two_code})  
    public void onClick(View view) {  
        switch (view.getId()) {  
            case R.id.btn_create:  
  
                String url = etUrl.getText().toString().trim();  
                Bitmap bitmap = ZXingUtils.createQRImage(url, ivTwoCode.getWidth(), ivTwoCode.getHeight());  
                ivTwoCode.setImageBitmap(bitmap);  

例如:

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\nVERSION:3.0\nORG:"+company+"\nTEL:"+phone+"\nURL:"+web+"\nEMAIL:"+email+"\nEND:VCARD";
            try {
                //调用方法createCode生成二维码
        Bitmap bm=createCode(contents, logo, BarcodeFormat.QR_CODE);
        

  

  

 

Android二维码之创建