- 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;
- }
- }
复制代码 |