为某个按钮或者图片添加点击事件,然后:strImg为图片url地址 ,loadDialog只是个提示信息,可以不要这个参数。使用Glide的onResourceReady方法获取到bitmap对象:
LoadDialog loadDialog=new LoadDialog(); loadDialog.initShow(context,"图片保存中");
public static void savePic(Context context, String strImg, LoadDialog loadDialog) {
if (!ObjectUtils.isEmpty(strImg)) {
//转化为位图
Glide.with(context).asBitmap().load(strImg).listener(new RequestListener<Bitmap>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
ToastUtils.showShort("图片加载失败,请使用手机截图");
loadDialog.dismiss();
return false;
}
@Override
public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
if (!ObjectUtils.isEmpty(resource)) {
try {
String string = Utils.getImgPath(context, resource, DateUtil.getCurrentTime("HHmmss"));
ToastUtils.showLong("图片保存位置:" + string);
} catch (Exception e) {
e.printStackTrace();
ToastUtils.showShort("图片保存失败,请使用手机截屏");
}
} else {
ToastUtils.showShort("图片获取失败,请使用手机截图");
Log.d("图片获取失败", "mBitmap == null");
}
loadDialog.dismiss();
return false;
}
}).submit();
}else ToastUtils.showShort("图片获取失败,请用手机截图");
}
保存图片并返回路径:
public static String getImgPath(Context context, Bitmap bitmap, String picName) {
String fileName = null;
//保存文件路径
String filePath = Environment.getExternalStorageDirectory().toString();
//适配Android 10
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
filePath = Objects.requireNonNull(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)).toString();
}
//系统相册目录
String galleryPath = (filePath
+ File.separator + Environment.DIRECTORY_DCIM
+ File.separator + "Camera" + File.separator);
// 声明文件对象
File file = null;
// 声明输出流
FileOutputStream outStream = null;
try {
// 如果有目标文件,直接获得文件对象,否则创建一个以filename为名称的文件
file = new File(galleryPath, picName + ".jpg");
// 获得文件相对路径
fileName = file.toString();
// 获得输出流,如果文件中有内容,追加内容
outStream = new FileOutputStream(fileName);
//图片压缩 质量为原来的90%,把压缩后的图片放到outStream
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
} catch (FileNotFoundException e) {
e.getStackTrace();
} finally {
if (outStream != null) {
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
MediaStore.Images.Media.insertImage(context.getContentResolver(),
bitmap, fileName, null);
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, galleryPath);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
// 通知图库更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
}
return file.getPath();
}
详细注释,放在代码里面了