0

我正在尝试(使用下面的方法)从互联网上获取图像并使用画布进行处理。但有时我遇到 outOfMemory 异常。所以我想知道是否有办法将 inputStream 直接加载到存储卡而不是内部存储器中。

private Bitmap LoadImageFromWebOperations(String url)
{   

   try {
        InputStream is = (InputStream) new URL(url).getContent();
        Drawable d = Drawable.createFromStream(is, "src name");
        bitmap = ((BitmapDrawable)d).getBitmap().copy(Config.ARGB_8888, true);
        return bitmap;
        }catch (Exception e) {
        System.out.println("Exc="+e);
        return null;
    }
}

logcat 说异常是由于该行:

Drawable d = Drawable.createFromStream(is, "src name");

提前谢谢!

4

1 回答 1

1

我从 Fedor Vlasov 的惰性列表演示中获取了这段代码: 在 ListView 中延迟加载图像

首先,您需要创建一个函数来将输入流复制到文件输出流:

public static void CopyStream(InputStream is, OutputStream os)
{
    final int buffer_size=1024;
    try
    {
        byte[] bytes=new byte[buffer_size];
        for(;;)
        {
          int count=is.read(bytes, 0, buffer_size);
          if(count==-1)
              break;
          os.write(bytes, 0, count);
        }
    }
    catch(Exception ex){}
}

然后得到一个缓存文件夹:

if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
        cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"MyCacheDir");
    else
        cacheDir=context.getCacheDir();
    if(!cacheDir.exists())
        cacheDir.mkdirs();

然后加载您的位图:

 private Drawable getBitmap(String url) 
{
    String filename=URLEncoder.encode(url);
    File f= new File(cacheDir, filename);

    try {                        
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        InputStream is = conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        CopyStream(is, os);
        os.close();            

        Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(f));            
        return new BitmapDrawable(bitmap);
    } catch (Exception ex){
       ex.printStackTrace();
       return null;
    }
} 
于 2012-07-05T09:34:52.770 回答