从ImageView获取图像并将其保存到SD卡

时间:2017-11-08 16:22:43

标签: android

我使用Glide从适配器加载图像

Glide
  .with(holder.messagePhoto.getContext())
  .load(currentMessage.getMessageText())
  .into(holder.messagePhoto);

我想将图像从imageView holder.messagePhoto保存到SD卡 我试过这个:

 String root = Environment.getExternalStorageDirectory().toString();
 File myDir = new File(root + "/req_images");

 myDir.mkdirs();
 Random generator = new Random();
 int n = 10000;
 n = generator.nextInt(n);
 String fname = "Image-" + n + ".jpg";
 File file = new File(myDir, fname);

 Log.i("saveIMG", "" + file);
 if (file.exists())
   file.delete();

 try {
   FileOutputStream out = new FileOutputStream(file);
   Bitmap  bm = ((BitmapDrawable) 
   holder.messagePhoto.getDrawable()).getBitmap();
   bm.compress(Bitmap.CompressFormat.JPEG, 0, out);

   out.flush();
   out.close();

 } catch (Exception e) {
     Log.i("saveIMGerror", e.getMessage() );
 }

但它显示错误:

Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference

1 个答案:

答案 0 :(得分:0)

Glide.with(context).asBitmap().load();

像这样滑行