Android开发之安卓二维码实现方法
relativelayout
xmlns:android=”https://schemas.android.com/apk/res/android”
xmlns:app=”https://schemas.android.com/apk/res-auto”
xmlns:tools=”https://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
tools:context=”.mainactivity”>
//工具类
package com.example.mytwoma;
import android.content.context;
import android.graphics.bitmap;
import android.graphics.bitmapfactory;
import android.graphics.canvas;
import android.graphics.color;
import com.google.zxing.barcodeformat;
import com.google.zxing.encodehinttype;
import com.google.zxing.writerexception;
import com.google.zxing.common.bitmatrix;
import com.google.zxing.qrcode.qrcodewriter;
import com.google.zxing.qrcode.decoder.errorcorrectionlevel;
import java.util.hashtable;
import java.util.random;
/**
* date:2016/7/27
* author:易宸锋(dell)
* function:
*/
public class bitmaputil {
/** * 根据指定内容生成自定义宽高的二维码图片 * * @param logobmp logo图标 * @param content 需要生成二维码的内容 * @param qr_width 二维码宽度 * @param qr_height 二维码高度 * @return 二维码的图片 * @throws writerexception 生成二维码异常 */ public static bitmap makeqrimage(bitmap logobmp, string content, int qr_width, int qr_height) throws writerexception { try { // 图像数据转换,使用了矩阵转换 hashtable hints = new hashtable(); hints.put(encodehinttype.character_set, "utf-8"); hints.put(encodehinttype.error_correction, errorcorrectionlevel.h);// 容错率 /*hints.put(encodehinttype.margin, 2); // default is 4 hints.put(encodehinttype.max_size, 350); hints.put(encodehinttype.min_size, 100);*/ bitmatrix bitmatrix = new qrcodewriter().encode(content, barcodeformat.qr_code, qr_width, qr_height, hints); int[] pixels = new int[qr_width * qr_height]; for (int y = 0; y < qr_height; y++) { // 下面这里按照二维码的算法,逐个生成二维码的图片,//两个for循环是图片横列扫描的结果 for (int x = 0; x < qr_width; x++) { if (bitmatrix.get(x, y)) { if (x < qr_width / 2 && y < qr_height / 2) { pixels[y * qr_width + x] = color.blue;// 蓝色 integer.tohexstring(new random().nextint()); } else if (x < qr_width / 2 && y > qr_height / 2) { pixels[y * qr_width + x] = color.red;// 红色 } else if (x > qr_width / 2 && y > qr_height / 2) { pixels[y * qr_width + x] = color.green;// 绿色 } else { pixels[y * qr_width + x] = color.cyan;// 青色 } } else { pixels[y * qr_width + x] = 0xffffffff;// 白色 } } } // ------------------添加图片部分------------------// bitmap bitmap = bitmap.createbitmap(qr_width, qr_height, bitmap.config.argb_8888); // 设置像素点 bitmap.setpixels(pixels, 0, qr_width, 0, 0, qr_width, qr_height); // 获取图片宽高 int logowidth = logobmp.getwidth(); int logoheight = logobmp.getheight(); if (qr_width == 0 || qr_height == 0) { return null; } if (logowidth == 0 || logoheight == 0) { return bitmap; } // 图片绘制在二维码*,合成二维码图片 // logo大小为二维码整体大小的1/5 float scalefactor = qr_width * 1.0f / 5 / logowidth; try { canvas canvas = new canvas(bitmap); canvas.drawbitmap(bitmap, 0, 0, null); canvas.scale(scalefactor, scalefactor, qr_width / 2, qr_height / 2); canvas.drawbitmap(logobmp, (qr_width - logowidth) / 2, (qr_height - logoheight) / 2, null); canvas.save(canvas.all_save_flag); canvas.restore(); return bitmap; } catch (exception e) { bitmap = null; e.getstacktrace(); } } catch (writerexception e) { e.printstacktrace(); } return null; } /** * 获取十六进制的颜色代码.例如 "#6e36b4" , for html , * * @return string 十六进制颜色代码 */ public static string getrandcolorcode() { string r, g, b; random random = new random(); r = integer.tohexstring(random.nextint(256)).touppercase(); g = integer.tohexstring(random.nextint(256)).touppercase(); b = integer.tohexstring(random.nextint(256)).touppercase(); r = r.length() == 1 ? "0" + r : r; g = g.length() == 1 ? "0" + g : g; b = b.length() == 1 ? "0" + b : b; return r + g + b; } /** * 根据指定内容生成自定义宽高的二维码图片 * * @param content 需要生成二维码的内容 * @param width 二维码宽度 * @param height 二维码高度 * @throws writerexception 生成二维码异常 */ public static bitmap makeqrimage(string content, int width, int height) throws writerexception { hashtable hints = new hashtable(); hints.put(encodehinttype.character_set, "utf-8"); // 图像数据转换,使用了矩阵转换 bitmatrix bitmatrix = new qrcodewriter().encode(content, barcodeformat.qr_code, width, height, hints); int[] pixels = new int[width * height]; // 按照二维码的算法,逐个生成二维码的图片,两个for循环是图片横列扫描的结果 for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (bitmatrix.get(x, y)) pixels[y * width + x] = 0xff000000; else pixels[y * width + x] = 0xffffffff; } } // 生成二维码图片的格式,使用argb_8888 bitmap bitmap = bitmap.createbitmap(width, height, bitmap.config.argb_8888); bitmap.setpixels(pixels, 0, width, 0, 0, width, height); return bitmap; } /** * 从资源文件中获取图片转化成bitmap类型 * * @param context 上下文 * @param drawableid 资源文件id * @return 转换后的图片 */ public static bitmap gainbitmap(context context, int drawableid) { bitmap bmp = bitmapfactory.decoderesource(context.getresources(), drawableid); return bmp; } /** * 在图片右下角添加水印 * * @param srcbmp 原图 * @param markbmp 水印88图片 * @return 合成水印后的图片 */ public static bitmap composewatermark(bitmap srcbmp, bitmap markbmp) { if (srcbmp == null) { return null; } // 创建一个新的和src长度宽度一样的位图 bitmap newb = bitmap.createbitmap(srcbmp.getwidth(), srcbmp.getheight(), bitmap.config.argb_8888); canvas cv = new canvas(newb); // 在 0,0坐标开始画入原图 cv.drawbitmap(srcbmp, 0, 0, null); // 在原图的右下角画入水印 cv.drawbitmap(markbmp, srcbmp.getwidth() - markbmp.getwidth() * 4 / 5, srcbmp.getheight() * 2 / 7, null); // 保存 cv.save(canvas.all_save_flag); // 存储 cv.restore(); return newb; } /** * 给二维码图片加背景 * * @param foreground * @param background * @return */ public static bitmap addbackground(bitmap foreground, bitmap background) { int bgwidth = background.getwidth(); int bgheight = background.getheight(); int fgwidth = foreground.getwidth(); int fgheight = foreground.getheight(); bitmap newmap = bitmap .createbitmap(bgwidth, bgheight, bitmap.config.argb_8888); canvas canvas = new canvas(newmap); canvas.drawbitmap(background, 0, 0, null); canvas.drawbitmap(foreground, (bgwidth - fgwidth) / 2, (bgheight - fgheight) * 3 / 5 + 70, null); canvas.save(canvas.all_save_flag); canvas.restore(); return newmap; }
}
//主代码
package com.example.mytwoma;
import android.annotation.targetapi;
import android.content.intent;
import android.graphics.bitmap;
import android.os.build;
import android.os.bundle;
import android.os.environment;
import android.support.annotation.requiresapi;
import android.support.v7.app.appcompatactivity;
import android.view.view;
import android.widget.button;
import android.widget.edittext;
import android.widget.imageview;
import android.widget.textview;
import android.widget.toast;
import com.google.zxing.writerexception;
import com.uuzuche.lib_zxing.activity.captureactivity;
import com.uuzuche.lib_zxing.activity.codeutils;
import java.io.file;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.outputstream;
import java.text.simpledateformat;
import java.util.date;
public class mainactivity extends appcompatactivity implements view.onclicklistener {
//开始扫码(按钮)
private button startscan_bt;
//扫码结果(文本)
private textview scancontent_tv;
//输入要生成二维码的内容(输入框)
private edittext generatecontent_et;
//开始生成二维码(按钮)
private button generate_bt;
//显示二维码(显示图片)
private imageview twodimensionalcode_iv;
//保存图片(按钮)
private button savebitmap_bt;
//生成的二维码放在这个bitmap里面 bitmap bitmap = null; //请求码 private final int requestcode = 0; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); //初始化 initview(); } /** * 对控件进行初始化. */ private void initview() { startscan_bt = (button) findviewbyid(r.id.startscan_bt); scancontent_tv = (textview) findviewbyid(r.id.scancontent_tv); generatecontent_et = (edittext) findviewbyid(r.id.generatecontent_et); generate_bt = (button) findviewbyid(r.id.generate_bt); twodimensionalcode_iv = (imageview) findviewbyid(r.id.twodimensionalcode_iv); //savebitmap_bt = (button) findviewbyid(r.id.savebitmap__bt); //设置监听事件 startscan_bt.setonclicklistener(this); generate_bt.setonclicklistener(this); } /** * 当两个按钮分别被点击时,做对应的处理. * * @param view */ @targetapi(build.version_codes.n) @override public void onclick(view view) { switch (view.getid()) { //点击扫描时,所做的操作 case r.id.startscan_bt: //弹个吐司. toast.maketext(mainactivity.this, "开始扫描二维码", toast.length_short).show(); //创建一个意图,,指定跳转到captureactivity页面,所以对应的要在清单文件里进行配置 intent intent = new intent(mainactivity.this, captureactivity.class); startactivityforresult(intent,5); break; //点击生成二维码时,所做的操作 case r.id.generate_bt: //得到edittext控件的用户输入信息,并进行非null判断. string content = generatecontent_et.gettext().tostring(); if (null == content || "".equals(content)) { toast.maketext(mainactivity.this, "输入内容不能为空", toast.length_short).show(); } else { //通过encodinghandler,调用createqrcode,有两个参数,一个字符串信息,一个设置生成图片的宽的值,因为二维码是正方形 try {
// bitmap = encodinghandler.createqrcode(content, twodimensionalcode_iv.getwidth());
bitmap = bitmaputil.makeqrimage(bitmaputil.gainbitmap(mainactivity.this, r.drawable.e),content, twodimensionalcode_iv.getwidth(), twodimensionalcode_iv.getheight());
} catch (writerexception e) {
e.printstacktrace();
toast.maketext(mainactivity.this, “由于未知原因,生成失败,请稍后重试”, toast.length_short).show();
return;
}
//通过方法得到一个bitmap,然后设置给imageview控件中.
twodimensionalcode_iv.setimagebitmap(bitmap);
}
break;
} } /** * 把毫秒转换时分秒 * * @param millis 毫秒 * @return 转换后的时分秒 */ @requiresapi(api = build.version_codes.n) public string getms_turn_date(long millis) { date date = new date(millis); simpledateformat sdf = new simpledateformat("yyyy年mm月dd日 hh:mm:ss"); return sdf.format(date); } /** * onactivityresult:得到captureactivity返回的结果进行处理. * * @param requestcode * @param resultcode * @param data */ @override protected void onactivityresult(int requestcode, int resultcode, intent data) { //对返回的响应码进行判断,== result_ok的话,成功得到结果 if(requestcode == 5 ){ //处理扫描结果(在界面上显示) if (null != data) { bundle bundle = data.getextras(); if (bundle == null) { return; } if (bundle.getint(codeutils.result_type) == codeutils.result_success) { string result = bundle.getstring(codeutils.result_string); toast.maketext(this, "解析结果:" + result, toast.length_long).show(); } else if (bundle.getint(codeutils.result_type) == codeutils.result_failed) { toast.maketext(mainactivity.this, "解析二维码失败", toast.length_long).show(); } } } super.onactivityresult(requestcode, resultcode, data); }
上一篇: 我成功创业的经验