2017-07-27 86 views
0
@Override 
public void onBindViewHolder(final ViewHolder holder ,int position) { 
    Glide.with(c) 
      .load(images.get(position)) 
      .placeholder(R.mipmap.ic_launcher) 
      .into(holder.img); 
    holder.img.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      try{ 
       String fileName = "bitmap.png"; 
       FileOutputStream stream = c.openFileOutput(fileName,Context.MODE_PRIVATE); 
       Intent showBigPicture = new Intent(c,showBigPicture.class); 
       Bitmap bitmapImage = BitmapFactory.decodeFile(images.get(position)); 
       bitmapImage.compress(Bitmap.CompressFormat.PNG,100,stream); 
       stream.close(); 
       bitmapImage.recycle(); 
       showBigPicture.putExtra("image",fileName); 
       c.startActivity(showBigPicture); 

      }catch (Exception e){ 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

这是在logcat中显示“无法解码流:java.io.FileNotFoundException:android.support.v7.widget.AppCompatImageView {e22d977 V.ED ... C:... P .... 0,0-540,890#7f0b0061 app:id/img}:打开失败:ENOENT(无此文件或目录)“我无法从recyclerview.adapter发送图像到另一个活动

+0

它看起来像只是将文件名传递给下一个活动。你有创建位图的原因吗? – ono

回答

0

我相信你想关注this answer保存位图图像。我相信你得到一个FileNotFoundException的原因是因为你正在提供一个URI到一个还不存在于decodeFile函数的文件中,这很可能是我所知道的一个URL。总之,为了节省位图:

  1. 创建的文件使用的getName从步骤1
  2. File(filename)
  3. 解码文件创建FileOutputStreamFile
  4. 压缩的位图图像到FileOutputStream

从我可以从你的问题中推测出来,它看起来好像你在RecyclerView中显示图像,当图像是点击,你想打开另一个显示完整图像版本的活动。如果这与您的用例非常接近,并且您正在使用Glide,我会建议您利用其内置的自动缓存功能来减少网络呼叫,而不是手动保存文件。

默认情况下,只要使用相同的文件名,路径或URL来获取每个Glide.load(...)上的映像,就会在Glide中启用磁盘和基于内存的缓存。如果你想操作的缓存是如何发生的,使用DiskCacheStrategy枚举来控制你每次加载图像:

Glide.with(c) 
     .load(images.get(position)) 
     .diskCacheStrategy(DiskCacheStrategy.SOURCE) # Will cache the source downloaded image before any transformations are applied 
     .placeholder(R.mipmap.ic_launcher) 
     .into(holder.img);  

如果你仍然想保存其他原因的文件,请使用SimpleTarget代替像这样直接加载到ImageView中:

Glide.with(c) 
     .load(images.get(position)) 
     .diskCacheStrategy(DiskCacheStrategy.SOURCE) # Will cache the source downloaded image before any transformations are applied 
     .placeholder(R.mipmap.ic_launcher) 
     .asBitmap() 
     .into(new SimpleTarget<GlideDrawable>() { 
        @Override 
        public void onResourceReady(Bitmap bitmap, GlideAnimation anim) { 
         holder.img.setImageDrawable(new BitmapDrawable(bitmap)); 
         saveImage(bitmap); # This being an encapsulation of the steps outlined earlier 
        } 
    }); 
+0

是的你是对的,我想在另一个活动中显示一个完整的图像,但我不知道如何使用.diskCacheStrategy来做到这一点。 – ray1195

+0

您只需在预览活动和全尺寸图像活动中的Glide加载器上使用该行即可。测试正确缓存的最佳方法是清除所有应用程序数据,加载预览活动以确保下载图像,然后关闭任何网络连接并尝试加载完整大小的活动。全尺寸活动中的图像仍应从缓存中保存的全尺寸图像加载 – shiv

相关问题