利用開源ZXing庫,在android上進行二維碼簡單的編碼和解碼

首先是簡單的編碼,代碼如下

/**
	 * 根據字符串進行二維編碼
	 * @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;
	}

點擊此處下載示例源碼

發佈了60 篇原創文章 · 獲贊 21 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章