阅读背景:

短视频程序保存图片到系统相册

来源:互联网 
package com.cardiar.xin_an_doctor_app.utils; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import android.text.TextUtils; import android.util.Log; import com.bumptech.glide.Glide; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * content 保存图片 */ public class SaveImageUtil { private String[] imageTypes = new String[]{".jpg", ".png", ".jpeg", "webp"}; //保存图片 public void saveImage(final String imageUrl, final Context context) { Log.e("图片", imageUrl); Glide.with(context).load(imageUrl).asBitmap().into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { // 创建目录 File appDir = new File(Environment.getExternalStorageDirectory(), "GadImage"); if (!appDir.exists()) { appDir.mkdirs(); } String imageType = getImageType(imageUrl); //获取图片类型 //System.currentTimeMillis()随机数 String name = null;//截取图片名 try { name = imageUrl.substring(imageUrl.lastIndexOf("/") + 1, imageUrl.lastIndexOf(".")); } catch (Exception e) { name = imageUrl.substring(imageUrl.lastIndexOf("/") + 1, imageUrl.length()); } String fileName = name + System.currentTimeMillis() + "." + imageType; File file = new File(appDir, fileName); if (!file.exists()) { //保存图片 try { FileOutputStream fos = new FileOutputStream(file); if (TextUtils.equals(imageType, "jpg")) { imageType = "jpeg"; } imageType = imageType.toUpperCase(); resource.compress(Bitmap.CompressFormat.valueOf(imageType), 100, fos); fos.flush(); fos.close(); ToastUtils.showToast(context, "图片已保存到GadImage"); } catch (FileNotFoundException e) { if (e.toString().endsWith(("(Permission denied)"))) { ToastUtils.showToast(context, "请前往应用权限管理打开储存权限"); } } catch (IOException e) { MyLog.e("dfdf", "onResourceReady: "); } // 其次把文件插入到系统图库 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.parse("file://" + file.getPath()))); } else { ToastUtils.showToast(context, "图片已存在"); } } }); } //图片类型 private String getImageType(String imageUrl) { String imageType; if (imageUrl.endsWith(imageTypes[0])) { imageType = "jpg"; } else if (imageUrl.endsWith(imageTypes[1])) { imageType = "png"; } else { imageType = "jpeg"; } return imageType; } } package com.cardiar.xin_an_doctor_app.utils; impo



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: