您的位置:首页 > 移动开发 > Android开发

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

2014-04-09 19:09 531 查看
首先是简单的编码,代码如下

/**
	 * 根据字符串进行二维编码
	 * @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;
	}

点击此处下载示例源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: