利用开源ZXing库,在android上进行二维码简单的编码和解码

本文介绍如何在Android应用中使用ZXing库进行二维码的编码和解码操作。通过提供的示例源码,读者可以快速理解并实现二维码的创建和读取功能。

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

首先是简单的编码,代码如下

/**
	 * 根据字符串进行二维编码
	 * @param str   需要编码的字符串
	 * @param widthAndHeight  需要生成的bitmap的高宽
	 * @return
	 */
	public Bitmap enCode(String str,int widthAndHeight){
	
			
			if (!str.equals("")&&str!=null)
				try {
					return EncodingHandler.createQRCode(str, widthAndHeight);
				} catch (WriterException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			else
				try {
					return EncodingHandler.createQRCode("null", widthAndHeight);
				} catch (WriterException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			return null;
	}

再次,是简单的解码,代码如下

	public String deCode(Bitmap bitmap) {		
		if(bitmap ==null){
			Log.i("deCode","-----------------------null");
			return "null";
		}
		Hashtable<DecodeHintType, Object> hints = null;
		initHints(hints, null, "UTF8");
		MultiFormatReader multiFormatReader = new MultiFormatReader();
		multiFormatReader.setHints(hints);


		LuminanceSource source = new BitmapLuance(bitmap);
		
		BinaryBitmap bit = new BinaryBitmap(new HybridBinarizer(source));
	
		try {
			return multiFormatReader.decodeWithState(bit).getText();

		} catch (ReaderException re) {
			// continue
		} finally {
			multiFormatReader.reset();
		}
		return null;
	}

	public void initHints(Hashtable<DecodeHintType, Object> hints,
			Vector<BarcodeFormat> decodeFormats, String CODE_STYLE) {
		hints = new Hashtable<DecodeHintType, Object>(2);
		if (decodeFormats == null || decodeFormats.isEmpty()) {
			decodeFormats = new Vector<BarcodeFormat>();
			decodeFormats.addAll(MyDecodeFormatManager.ONE_D_FORMATS);
			decodeFormats.addAll(MyDecodeFormatManager.QR_CODE_FORMATS);
			decodeFormats.addAll(MyDecodeFormatManager.DATA_MATRIX_FORMATS);
		}
		hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
		if (CODE_STYLE != null) {
		
			//hints.put(DecodeHintType.CHARACTER_SET, CODE_STYLE);
		}

	}

	private Bitmap fileToBitmap(String imgpath) {

		Bitmap bm = BitmapFactory.decodeFile(imgpath);
		return bm;
	}

点击此处下载示例源码

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值