2017-07-27 69 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

相關問題