二维码的生成和扫描

1.二维码的生成

复制代码
private ImageView iv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    iv = ((ImageView) findViewById(R.id.iv));
}

public void btnClick(View view) {
    //1.数据源
    //2.生成的Bitmap的宽度
    //3.生成的Bitmap的高度
    Bitmap bitmap = getQRCodeBitmap("祝大家找到一个好工作!", 400, 400);
    iv.setImageBitmap(bitmap);
}

private Bitmap getQRCodeBitmap(String content, int width, int height) {
    QRCodeWriter writer = new QRCodeWriter();
    Map<EncodeHintType, String> hint = new HashMap<>();
    //文本的编码格式为UTF-8
    hint.put(EncodeHintType.CHARACTER_SET, "utf-8");
    //将文本信息转换为二维码
    //1.数据源
    //2.转换为二维码
    //3.4.生成的二维数据的宽高
    //5.文本的编码格式
    try {
        //encode的返回结果是一个二维数组,该数组中保存着转换后的数据信息
        BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hint);
        int[] pixles = new int[width * height];
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                //该点如果有数据则返回true,否则返回false
                if (bitMatrix.get(j, i)) {
                    //如果该点有数据,则该点为黑色
                    pixles[i * width + j] = 0x00000000;
                } else {
                    pixles[i * width + j] = 0xffffffff;
                }
            }
        }
        //1.Bitmap中所有的像素点信息
        //2.偏移量
        //3.生成的Bitmap每行有多少个像素点
        //4.5.生成的Bitmap的宽高
        //6.色彩模式
        return Bitmap.createBitmap(pixles, 0, width, width, height, Bitmap.Config.RGB_565);
    } catch (WriterException e) {
        e.printStackTrace();
    }
    return null;
}
复制代码

2.二维码的扫描

步骤:

第一步:下载并解压zxing-master.zip

第二步:将下面两个文件夹中的com文件夹添加到工程的java下

第三步:接下来都是android文件夹下,如下文件没有的直接拷贝,已有的进行合并

第四步:将错误的包名修改正确

第五步:MainActivity中代码

 public void go(View view) {
        startActivity(new Intent(this, CaptureActivity.class));
    }

 

posted @   嘉禾世兴  阅读(277)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示