2016-02-01 86 views
0

我想使用Glide將位圖保存到文件,然後用一個漂亮的共享按鈕分享圖片。我使用一些代碼,我已經在文檔中發現的,就像這樣:滑動保存圖片到文件 - 位圖回收

Glide.with(getApplicationContext()) 
      .load(imageUrl) 
      .asBitmap() 
      .into(new SimpleTarget<Bitmap>() { 
       @Override 
       public void onResourceReady(Bitmap b, GlideAnimation<? super Bitmap> glideAnimation) { 
        File file = getExternalFilesDir(null); 
        try { 
         URI uri = new URI(imageUrl); 
         String path = uri.getPath(); 
         String nameOfFile = file + "/" + path.substring(path.lastIndexOf('/') + 1); 
         OutputStream os = new FileOutputStream(nameOfFile); 
         b.compress(Bitmap.CompressFormat.JPEG, 100, os); 
         os.flush(); 
         os.close(); 

         Intent share = new Intent(Intent.ACTION_SEND); 
         share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + nameOfFile)); 
         share.setType("image/*"); 
         startActivity(Intent.createChooser(share, getResources().getString(R.string.action_share))); 
        } catch (IOException | URISyntaxException e) { 
         e.printStackTrace(); 
        } 
       } 
      }); 

的事情是,隨機,應用程序崩潰,因爲位圖b的之前,我壓縮它回收。我怎樣才能避免這種情況?有沒有更好的辦法?

回答

0

我和你有類似的問題。 也許你生成一個位圖在其他地方使用相同的imageUrl,然後你手動調用bitmap.recycled()。所以你叫asBitmap()可能會導致位圖回收問題。

你可以用asFile()替換asBitmap();

.asFile() 
     .into(new SimpleTarget<File>() 

或完全不需要bitmap.recycled()