安卓将URL链接生成二维码保存到本地相册
/*
*context不解释;url:要转二维码的链接;width,height也不解释;originalid:二维码图片的名字
*/
public static String createQRImage(Context context, String url, final int width, final int height, String oirginalid) {
try {
// 判断URL合法性
if (url == null || "".equals(url) || url.length() < 1) {
return "fail";
}
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 图像数据转换,使用了矩阵转换
BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, width, height, hints);
int[] pixels = new int[width * height];
// 下面这里按照二维码的算法,逐个生成二维码的图片,
// 两个for循环是图片横列扫描的结果
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * width + x] = 0xff000000;
} else {
pixels[y * width + x] = 0xffffffff;
}
}
}
// 生成二维码图片的格式,使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
/* String paths = "";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File external = context.getExternalFilesDir(null);
if (external != null) {
paths = external.getAbsolutePath();
}else{
paths = context.getFilesDir().getAbsolutePath();
}
}else{
paths = context.getFilesDir().getAbsolutePath();
}*/
/*String paths= Environment.getExternalStorageDirectory()
+ File.separator + Environment.DIRECTORY_DCIM
+File.separator+"Camera"+File.separator;*/
//File appDir = new File(paths);
//File appDir = new File(Environment.getExternalStorageDirectory(), "Test");
//File appDir = new File(Environment.getExternalStorageDirectory(), "DCIM");
File appDir = new File(Environment.getExternalStorageDirectory(), "Pictures");
if (!appDir.exists()) {
appDir.mkdirs();
}
String fileName = oirginalid + ".png";
android.util.Log.i("maptrix", "@#$%^&*------------------------bindphone message----------------------------"+fileName+"---"+appDir.getAbsolutePath());
File file = new File(appDir, fileName);
try {
if(!file.exists()){
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
bitmap.recycle();
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return "fail";
} catch (IOException e) {
e.printStackTrace();
return "fail";
}
bitmap.recycle();
// 其次把文件插入到系统图库
String path = file.getAbsolutePath();
filePath = path;
/*try {
MediaStore.Images.Media.insertImage(context.getContentResolver(), path, fileName, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
return "fail";
}*/
// 最后通知图库更新
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(file);
intent.setData(uri);
context.sendBroadcast(intent);
return path;
} catch (WriterException e) {
e.printStackTrace();
return "fail";
}
}
注意:第一,关于文件读写,对应用权限做好处理。第二,有个刷新图库那步我注释掉了,不需要,否则会出现又重新搞了一张二维码出来。
