Andriod二维码的生成和保存

来源:互联网 发布:召唤师捏脸数据 编辑:程序博客网 时间:2024/05/17 22:36

前端生成二维码,根据后台的一个支付的url来生成,使用zxing.jar

过程很简单,直接上代码

public class EncodingHandler
{


private static final int BLACK = 0xff000000;
private static final int WHITE = 0xffffffff;
public static Bitmap createQRCode(String str,int widthAndHeight) throws WriterException {
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();  
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); 
BitMatrix matrix = new MultiFormatWriter().encode(str,
BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight);
int width = matrix.getWidth();
int height = matrix.getHeight();
int[] pixels = new int[width * height];

for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (matrix.get(x, y)) {
pixels[y * width + x] = BLACK;
}else{
pixels[y * width + x] = WHITE;
}
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}


}

再一个就是使用了,两行代码搞定

Bitmap qrcodeBitmap = EncodingHandler.createQRCode(payurl, 600);
ivcode.setImageBitmap(qrcodeBitmap);

保存的时候写一个方法

public void saveImage(Context context, Bitmap bmp) {
   // 保存文件
   File appDir = new File(Environment.getExternalStorageDirectory(), "test");
   if (!appDir.exists()) {
       appDir.mkdir();
   }
  // String fileName = System.currentTimeMillis() + ".jpg";
   String fileName = "订单"+sorderid + ".jpg";
   File file = new File(appDir, fileName);
   try {
       FileOutputStream fos = new FileOutputStream(file);
       bmp.compress(CompressFormat.JPEG, 100, fos);
       fos.flush();
       fos.close();
       //Toast.makeText(CodePayActivity.this, "保存成功", 0).show();
   } catch (FileNotFoundException e) {
       e.printStackTrace();
   } catch (IOException e) {
       e.printStackTrace();
}
   // 其次把文件插入到系统图库
   try {
       MediaStore.Images.Media.insertImage(context.getContentResolver(),
file.getAbsolutePath(), fileName, null);
   } catch (FileNotFoundException e) {
       e.printStackTrace();
   }
   // 最后通知图库更新
   context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
   Toast.makeText(CodePayActivity.this, "保存成功", 0).show();
}

0 0