任务需求
产品需求是点击下载图片,将公司的二维码存储到用户手机中;
逻辑整理
实际上这张二维码没有走网络,只是在项目的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();
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();
}
|