2016-07-26 35 views
0

我下载的位图是这样的:加载位图有效地从内部存储,而不是资源的

HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
... 
InputStream input = connection.getInputStream(); 
Bitmap myBitmap = BitmapFactory.decodeStream(input); 

并将其保存到内部存储这样的:

fos = new FileOutputStream(filePath); 
image.compress(Bitmap.CompressFormat.JPEG, 90, fos); 

但研究google page about bitmaps之后,说下载一个大的位图到内存中可能会抛出一个outOfMemory异常,所以我应该缩放这个位图来占用内存上更小的空间。问题是,页面上的代码仅解释如何使用资源图像来完成此操作,而不是来自内部存储器的图像。所以,我有两个问题:

如何从内部存储位图?

而且

有没有一种方法来下载和保存图像都以某种方式?

我第一次创建一个位图图像,然后将它传递给将保存它的方法,所以我假设图像被完全加载到内存中,然后它被保存到内部存储。

+0

扔掉BitmapFactory。 Indead应该创建一个循环,从输入流中读取块并将它们直接写入文件输出流。 – greenapps

+0

你正在谈论'内部记忆',但是如果这成为现实,我们就无法在'filePath'上看到。 – greenapps

+0

它看起来不像加载位图的问题。 – greenapps

回答

0

从内部存储器加载图像不是问题,除非像在ViewPager中一次加载大量图像。或者你的图像真的很大。但如果不是这样的话,你应该没问题。

关于下载图片,我强烈建议您不要选择“全部以单向方式”。因为面向对象编程。此外,请尝试使用Volley下载您的图像。

+0

我正在从内部存储中加载它们,但它们像800x600图像一样适合消息的50x50圆形图像视图,就像gmail一样,所以我真的应该处理它们。没有一种简单的方法可以在不使用Volley的情况下将图像写入零件?我真的需要一个小的解决方案。我认为,为位图处理解决了,我没有看到一个方法decodeFile存在,我认为这只是decodeResource https://developer.android.com/reference/android/graphics/BitmapFactory.html#decodeFile(java .lang.String) – Gatonito

+0

@Gatonito实际上你真正需要做的是计算样本大小。 在这里,https://developer.android.com/training/displaying-bitmaps/load-bitmap.html – klutch

0

你可以用初级讲座代码尝试:

public void loadPhotoToView(String path) { 
     File imgFile = new File(path); 
     if (imgFile.exists()) { 
      imageView.setImageBitmap(decodeFile(imgFile)); 
     } 
    } 

    // Decode image and scale it to reduce memory consumption 
    public Bitmap decodeFile(File f) { 
     try { 
      BitmapFactory.Options o = new BitmapFactory.Options(); 
      o.inJustDecodeBounds = true; 
      BitmapFactory.decodeStream(new FileInputStream(f), null, o); 

      // The new size we want to scale to, the bigger the better of quality 
      final int REQUIRED_SIZE = 200; 

      // Find the correct scale value. It should be the power of 2. 
      int scale = 1; 
      while (o.outWidth/scale/2 >= REQUIRED_SIZE && 
        o.outHeight/scale/2 >= REQUIRED_SIZE) { 
       scale *= 2; 
      } 

      // Decode with inSampleSize 
      BitmapFactory.Options o2 = new BitmapFactory.Options(); 
      o2.inSampleSize = scale; 
      return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); 
     } catch (FileNotFoundException e) { 
     } 
     return null; 
    } 

另一种方法是使用一个库如毕加索加载图像:

Picasso.with(this).load(imgFile).into(imageView);