任务需求
产品需求是点击下载图片,将公司的二维码存储到用户手机中;
逻辑整理
实际上这张二维码没有走网络,只是在项目的res文件夹中缓存着。点击后将会读取bitmap资源然后重新存储到相册中。
代码实现
public void saveImageToGallery(Context context,ImageDownLoadCallBack imageDownLoadCallBack) {
callBack = imageDownLoadCallBack;
//获取二维码图片资源
Bitmap bitmap = BitmapFactory.decodeStream(getClass().getResourceAsStream("/res/drawable/wechat_qr_consult.jpg"));
// 文件路径资源加载
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();//注意小米手机必须这样获得public绝对路径
String fileName = "Zego";//图片存储的文件夹名字
File appDir = new File(file ,fileName);
if (!appDir.exists()) {
appDir.mkdirs();
}
fileName = System.currentTimeMillis() + ".jpg";
currentFile = new File(appDir, fileName);
FileOutputStream fos = null;
//判断是否已经下载到相册中,如果存在直接回调存在即可,反之就进行存储在相册操作
//进行存储操作
try {
fos = new FileOutputStream(currentFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭文件流
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//加载回调
if (bitmap != null && currentFile.exists()) {
callBack.onDownLoadSuccess(bitmap);
} else {
callBack.onDownLoadFailed();
}
// 最后通知图库更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.fromFile(new File(currentFile.getPath()))));
}
public interface ImageDownLoadCallBack {
void onDownLoadSuccess(Bitmap bitmap);
void onDownLoadFailed();
}