Android保存图片到本地
需求
一个很常见的需求,查看大图的同时,点击可以将图片保存到本地
我的步骤
- 使用Gilde获取图片的Drawable
- Drawable转成Bitmap
- bigtmap压缩并通过流写入
- 通知系统图库更新
代码块
- 保存图片,流写入,压缩
public static void saveImageToGallery(Context context, Bitmap bmp) {
// 首先保存图片
File appDir = new File(Environment.getExternalStorageDirectory(), "nongfaziran");
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} 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.fromFile(new File(file.getPath()))));
ToastUtil.showShort("保存到" + file.getPath());
}`
通过glide回调,获取图片Drawable
mTvSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showLoadding();
GlideUtils.loadImage(Utils.getContext(), urls.get(mViewPager.getCurrentItem()), mIvImg,new GlideUtils.ImageLoadListener<String, GlideDrawable>() {
@Override
public void onLoadingComplete(String uri, ImageView view, GlideDrawable resource) {
hideLoadding();
FileUtils.saveImageToGallery(Utils.getContext(), BitmapUtils.drawableToBitmap(resource));
showState("保存成功",1);
}
@Override
public void onLoadingError(String source, Exception e) {
hideLoadding();
showState("保存失败",0);
ToastUtil.showShort("请检查SD卡并检查网络");
}
});
}
});
分享一个Glide封装
/**
* Glide封装类
* Created by fengan on 2017/5/6.
* Last Update on 2017.6.22 。 添加注解提醒、返回类型、优化代码
*/
public abstract class GlideUtils {
/**
* 简单图片加载回调
*
* @param <T> 图片url 或资源id 或 文件
* @param <K> 返回的资源,GlideDrawable或者Bitmap或者GifDrawable,ImageView.setImageRecourse设置
*/
public interface ImageLoadListener<T, K> {
/**
* 图片加载成功回调
*
* @param uri 图片url 或资源id 或 文件
* @param view 目标载体,不传则为空
* @param resource 返回的资源,GlideDrawable或者Bitmap或者GifDrawable,ImageView.setImageRecourse设置
*/
void onLoadingComplete(T uri, ImageView view, K resource);
/**
* 图片加载异常返回
*
* @param source 图片地址、File、资源id
* @param e 异常信息
*/
void onLoadingError(T source, Exception e);
}
/**
* 详细加载图片加载回调
*
* @param <T> 图片url 或资源id 或 文件
* @param <K> 返回的资源
*/
public interface ImageLoadDetailListener<T, K> {
/**
* 图片加载成功回调
*
* @param uri 图片url 或资源id 或 文件
* @param view 目标载体,不传则为空
* @param resource 返回的资源,GlideDrawable或者Bitmap或者GifDrawable,ImageView.setImageRecourse设置
*/
void onLoadingComplete(T uri, ImageView view, K resource);
/**
* 图片加载异常返回
*
* @param source 图片地址、File、资源id
* @param errorDrawable 加载错误占位图
* @param e 异常信息
*/
void onLoadingEr