Android生成二维码

概述:

    使用Zxing的jar包,生成带logo的二维码图片。

效果图:

这里写图片描述

核心代码如下:

package com.example.qrcodesample.core;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Environment;
import android.widget.ImageView;

import com.example.qrcodesample.R;
import com.example.qrcodesample.util.LogUtil;
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;

/**
 * 生成二维码工具类
 * 
 * @author lincoln
 * 
 */
public class ZxingCreateInstance {
    private String content = "二维码内容";// 二维码默认内容
    private int widthPix = 600, heightPix = 600;// 二维码默认宽,高
    private Bitmap logoBitmap = null;// 中间logo图标
    private static ZxingCreateInstance instance = null;
    private Activity activity = null;
    private String filePath = "";

    public ZxingCreateInstance(Activity activity, String content) {
        this.activity = activity;
        this.content = content;
        filePath = getFileRoot() + File.separator + "qr_" + System.currentTimeMillis() + ".jpg";
    }

    public static ZxingCreateInstance Instance(Activity activity, String content) {
        if (instance == null) {
            instance = new ZxingCreateInstance(activity, content);
        }
        return instance;
    }

    /**
     * 生成二维码
     */
    private boolean createQRImage() {
        try {
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

            BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix, heightPix, hints);
            int[] pixels = new int[widthPix * heightPix];
            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;
                    }
                }
            }

            Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);

            if (logoBitmap != null) {
                bitmap = addLogo(bitmap, logoBitmap);
            }

            // 必须使用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 Bitmap addLogo(Bitmap src, Bitmap logo) {
        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;
        }

        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;
    }

    /**
     * 单例入口
     */
    public void createImage(final ImageView imageView) {
        // 耗时操作,启动线程生成二维码
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean success = createQRImage();

                if (imageView != null) {
                    final Bitmap bitmap = (BitmapFactory.decodeFile(filePath));

                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            imageView.setImageBitmap(bitmap);
                        }
                    });
                }

                if (success) {
                    LogUtil.d("create success");
                }
            }
        }).start();
    }

    // 文件存储根目录
    private String getFileRoot() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File external = activity.getExternalFilesDir(null);
            if (external != null) {
                return external.getAbsolutePath();
            }
        }
        return activity.getFilesDir().getAbsolutePath();
    }

    /**
     * 参数设置
     */
    public void setWH(int width, int height) {
        widthPix = width;
        heightPix = height;
    }

    /**
     * 设置中心logo图标
     * 
     * @param logoSrc
     */
    public void setLogoSrc(int logoSrc) {
        logoBitmap = BitmapFactory.decodeResource(activity.getResources(), logoSrc);
    }
}

使用方法:

ZxingCreateInstance instance = ZxingCreateInstance.Instance(this, "二维码内容");
instance.setLogoSrc(R.drawable.liuyan);
instance.setWH(1000, 1000);
instance.createImage(imageView);

完整代码

完整代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值