2016-02-01 87 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()