长按识别图中二维码

本文介绍了如何实现在Android应用中实现长按识别二维码的功能。通过监听长按事件,保存当前屏幕截图,然后解析截图中的二维码,展示识别结果。详细步骤包括获取屏幕截图、解析二维码图片以及使用QRCodeReader进行解码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

iv_zxingimag  .setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View viewm) {
        saveCurrentImage();
        return false;
    }
});

private void saveCurrentImage() {
    //获取当前屏幕的大小
    int width = getWindow().getDecorView().getRootView().getWidth();
    int height = getWindow().getDecorView().getRootView().getHeight();
    //生成相同大小的图片
    Bitmap temBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    //找到当前页面的根布局
    View view = getWindow().getDecorView().getRootView();
    //设置缓存
    view.setDrawingCacheEnabled(true);
    view.buildDrawingCache();
    //从缓存中获取当前屏幕的图片,创建一个DrawingCache的拷贝,因为DrawingCache得到的位图在禁用后会被回收
    temBitmap = view.getDrawingCache();
    SimpleDateFormat df = new SimpleDateFormat("yyyymmddhhmmss");
    final String time = df.format(new Date());
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/screen", time + ".png");
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            temBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/screen/" + time + ".png";
                final Result result = parseQRcodeBitmap(path);
                runOnUiThread(new Runnable() {
                    public void run() {
                        if (null != result) {
                            Toast.makeText(TakewayActivity.this, result.toString(), Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(TakewayActivity.this, "无法识别", Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }
        }).start();
        //禁用DrawingCahce否则会影响性能 ,而且不禁止会导致每次截图到保存的是第一次截图缓存的位图
        view.setDrawingCacheEnabled(false);
    }
}
//解析二维码图片,返回结果封装在Result对象中
private Result parseQRcodeBitmap(String bitmapPath) {
    //解析转换类型UTF-8
    Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
    hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
    //获取到待解析的图片
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeFile(bitmapPath, options);
    options.inSampleSize = options.outHeight / 400;
    if (options.inSampleSize <= 0) {
        options.inSampleSize = 1; //防止其值小于或等于0
    }
    options.inJustDecodeBounds = false;
    bitmap = BitmapFactory.decodeFile(bitmapPath, options);
    //新建一个RGBLuminanceSource对象,将bitmap图片传给此对象
    RGBLuminanceSource rgbLuminanceSource = new RGBLuminanceSource(bitmap);
    //将图片转换成二进制图片
    BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(rgbLuminanceSource));
    //初始化解析对象
    QRCodeReader reader = new QRCodeReader();
    //开始解析
    Result result = null;
    try {
        result = reader.decode(binaryBitmap, hints);
    } catch (Exception e) {
        // TODO: handle exception
    }
    return result;
}
public class RGBLuminanceSource extends LuminanceSource {

    private byte bitmapPixels[];

    protected RGBLuminanceSource(Bitmap bitmap) {
        super(bitmap.getWidth(), bitmap.getHeight());

        // 首先,要取得该图片的像素数组内容
        int[] data = new int[bitmap.getWidth() * bitmap.getHeight()];
        this.bitmapPixels = new byte[bitmap.getWidth() * bitmap.getHeight()];
        bitmap.getPixels(data, 0, getWidth(), 0, 0, getWidth(), getHeight());

        // int数组转换为byte数组,也就是取像素值中蓝色值部分作为辨析内容
        for (int i = 0; i < data.length; i++) {
            this.bitmapPixels[i] = (byte) data[i];
        }
    }

    @Override
    public byte[] getMatrix() {
        // 返回我们生成好的像素数据
        return bitmapPixels;
    }

    @Override
    public byte[] getRow(int y, byte[] row) {
        // 这里要得到指定行的像素数据
        System.arraycopy(bitmapPixels, y * getWidth(), row, 0, getWidth());
        return row;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值