我正试图抓住(使用下面的方法)来自互联网的图像并做一些画布工作。但有时我有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");
提前谢谢!
答案 0 :(得分:1)
我从Fedor Vlasov的lazylist演示中获取了这段代码: Lazy load of images in 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;
}
}