欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 点击生成二维码功能实现代码

程序员文章站 2023-08-12 13:07:01
先看效果: 输入内容,点击生成二维码: 点击logo图案: 代码: qrcodeutil: package com.example.admin...

先看效果:

Android 点击生成二维码功能实现代码

输入内容,点击生成二维码:

Android 点击生成二维码功能实现代码

点击logo图案:

Android 点击生成二维码功能实现代码

代码:

qrcodeutil:

package com.example.administrator.zxing;
import android.graphics.bitmap;
import android.graphics.canvas;
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.io.fileoutputstream;
import java.io.ioexception;
import java.util.hashmap;
import java.util.map;
public class qrcodeutil {
  public static boolean createqrimage(string content, int widthpix, int heightpix, bitmap logobm, string filepath) {
    try {
      if (content == null || "".equals(content)) {
        return false;
      }
      //配置参数
      map<encodehinttype, object> hints = new hashmap<>();
      hints.put(encodehinttype.character_set, "utf-8");
      //容错级别
      hints.put(encodehinttype.error_correction, errorcorrectionlevel.h);
      //设置空白边距的宽度
//      hints.put(encodehinttype.margin, 2); //default is 4
      // 图像数据转换,使用了矩阵转换
      bitmatrix bitmatrix = new qrcodewriter().encode(content, barcodeformat.qr_code, widthpix, heightpix, hints);
      int[] pixels = new int[widthpix * heightpix];
      // 下面这里按照二维码的算法,逐个生成二维码的图片,
      // 两个for循环是图片横列扫描的结果
      for (int y = 0; y < heightpix; y++) {
        for (int x = 0; x < widthpix; x++) {
          if (bitmatrix.get(x, y)) {
            pixels[y * widthpix + x] = 0xff000000;
          } else {
            pixels[y * widthpix + x] = 0xffffffff;
          }
        }
      }
      // 生成二维码图片的格式,使用argb_8888
      bitmap bitmap = bitmap.createbitmap(widthpix, heightpix, bitmap.config.argb_8888);
      bitmap.setpixels(pixels, 0, widthpix, 0, 0, widthpix, heightpix);
      if (logobm != null) {
        bitmap = addlogo(bitmap, logobm);
      }
      //必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的,内存消耗巨大!
      return bitmap != null && bitmap.compress(bitmap.compressformat.jpeg, 100, new fileoutputstream(filepath));
    } catch (writerexception | ioexception e) {
      e.printstacktrace();
    }
    return false;
  }
  /**
   * 在二维码中间添加logo图案
   */
  private static bitmap addlogo(bitmap src, bitmap logo) {
    if (src == null) {
      return null;
    }
    if (logo == null) {
      return src;
    }
    //获取图片的宽高
    int srcwidth = src.getwidth();
    int srcheight = src.getheight();
    int logowidth = logo.getwidth();
    int logoheight = logo.getheight();
    if (srcwidth == 0 || srcheight == 0) {
      return null;
    }
    if (logowidth == 0 || logoheight == 0) {
      return src;
    }
    //logo大小为二维码整体大小的1/5
    float scalefactor = srcwidth * 1.0f / 5 / logowidth;
    bitmap bitmap = bitmap.createbitmap(srcwidth, srcheight, bitmap.config.argb_8888);
    try {
      canvas canvas = new canvas(bitmap);
      canvas.drawbitmap(src, 0, 0, null);
      canvas.scale(scalefactor, scalefactor, srcwidth / 2, srcheight / 2);
      canvas.drawbitmap(logo, (srcwidth - logowidth) / 2, (srcheight - logoheight) / 2, null);
      canvas.save(canvas.all_save_flag);
      canvas.restore();
    } catch (exception e) {
      bitmap = null;
      e.getstacktrace();
    }
    return bitmap;
  }
}

mainactivity:

package com.example.administrator.zxing;
import android.content.context;
import android.graphics.bitmapfactory;
import android.os.bundle;
import android.os.environment;
import android.support.v7.app.appcompatactivity;
import android.view.view;
import android.widget.button;
import android.widget.checkbox;
import android.widget.edittext;
import android.widget.imageview;
import java.io.file;
public class mainactivity extends appcompatactivity {
  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
    //内容
    final edittext contentet = (edittext) findviewbyid(r.id.create_qr_content);
    //显示二维码图片
    final imageview imageview = (imageview) findviewbyid(r.id.create_qr_iv);
    //是否添加logo
    final checkbox addlogocb = (checkbox) findviewbyid(r.id.create_qr_addlogo);
    button createqrbtn = (button) findviewbyid(r.id.create_qr_btn);
    createqrbtn.setonclicklistener(new view.onclicklistener() {
      @override
      public void onclick(view v) {
        final string filepath = getfileroot(mainactivity.this) + file.separator
            + "qr_" + system.currenttimemillis() + ".jpg";
        //二维码图片较大时,生成图片、保存文件的时间可能较长,因此放在新线程中
        new thread(new runnable() {
          @override
          public void run() {
            boolean success = qrcodeutil.createqrimage(contentet.gettext().tostring().trim(), 800, 800,
                addlogocb.ischecked() ? bitmapfactory.decoderesource(getresources(), r.mipmap.qr_logo) : null,
                filepath);
            if (success) {
              runonuithread(new runnable() {
                @override
                public void run() {
                  imageview.setimagebitmap(bitmapfactory.decodefile(filepath));
                }
              });
            }
          }
        }).start();
      }
    });
  }
  //文件存储根目录
  private string getfileroot(context context) {
    if (environment.getexternalstoragestate().equals(environment.media_mounted)) {
      file external = context.getexternalfilesdir(null);
      if (external != null) {
        return external.getabsolutepath();
      }
    }
    return context.getfilesdir().getabsolutepath();
  }
}

布局:

 activity_main:

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  tools:context="com.example.administrator.zxing.mainactivity">
  <edittext
    android:id="@+id/create_qr_content"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
  <linearlayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <button
      android:id="@+id/create_qr_btn"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="生成二维码" />
    <checkbox
      android:id="@+id/create_qr_addlogo"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="添加logo图案" />
  </linearlayout>
  <imageview
    android:id="@+id/create_qr_iv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
</linearlayout>

总结

以上所述是小编给大家介绍的android 点击生成二维码功能实现代码,希望对大家有所帮助