黑马程序员技术交流社区
标题:
Android二维码生成和解析
[打印本页]
作者:
老衲玩IT
时间:
2013-8-27 14:15
标题:
Android二维码生成和解析
public class MainActivity extends Activity{
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
//加密二维码
encodeQRcode("sdcard/hwy.jpg","http://bbs.itheima.com/forum-93-1.html");
//解码二维码
Log.v("Decode",decodeQRcode("sdcard/hwy.jpg"));
}
/**
* 把相关信息加密成二维码图片
* @param saveImgPath 图片的保存位置
* @param content 要生成的二维码内容
*/
public static void encodeQRcode(String saveImgPath,String content) {
encodeQRCode(saveImgPath,content,150,150);
}
/**
* 把相关信息加密成图片,并指定生成图片的大小
* @param saveImgPath 二给码图片保存位置
* @param content 二给码的内容
*/
public static void encodeQRCode(String saveImgPath,String content,int width,int height) {
try {
BitMatrix byteMatrix = new MultiFormatWriter().encode(
new String(content.getBytes("GBK"),"iso-8859-1"),BarcodeFormat.QR_CODE, width, height);
MatrixToImageWriter.writeToFile(byteMatrix, "jpg", new File(saveImgPath));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 把指定的二维码图片解码为字符串信息
*/
public static String decodeQRcode(String imgPath) {
try {
File file = new File(imgPath);
try {
BufferedImage image = ImageIO.read(file);
if (image == null) {
System.out.println("找不到解码图片");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable<DecodeHintType,String> hints = new Hashtable<DecodeHintType,String>();
hints.put(DecodeHintType.CHARACTER_SET, "GBK");
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ReaderException re) {
re.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
复制代码
作者:
许庭洲
时间:
2013-8-27 19:11
值得学习ing!
作者:
月无心
时间:
2013-11-7 21:22
请问楼主, BufferedImage image在android中怎么引用的?
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2