首先是簡單的編碼,代碼如下
/**
* 根據字符串進行二維編碼
* @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;
}