0

I'm trying to grab (with the method below) an image from the internet and do some canvas work with. but sometimes i'm having outOfMemory exception. So i'm wondering if is there a way to load the inputStream directly in the memory card instead of the internal memory.

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;
    }
}

the logcat says that the exception is due to that line :

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

Thx in advance!

Christian
  • 1,258
  • 10
  • 11
youssoua
  • 802
  • 1
  • 11
  • 20

1 Answers1

1

I took this code from Fedor Vlasov's lazylist demo: Lazy load of images in ListView.

First you need to create a function to copy your input stream to file output stream:

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){}
}

Then get a cache folder:

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();

Then load your bitmap:

 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;
    }
} 
Community
  • 1
  • 1