2012-07-27 132 views
0

我有一个Android应用程序从MySQL数据库加载多个图像到ImageButton。bitmapfactory无法加载图像

imageButton.setImageBitmap(fetchBitmap("http://www...~.jpg")); 

我曾经能够成功加载PNG,但现在也失败了(没有成功的JPG图像)。下面是我使用的下载图像的代码: -

public static Bitmap fetchBitmap(String urlstr) { 
    InputStream is= null; 
    Bitmap bm= null; 
    try{ 
     HttpGet httpRequest = new HttpGet(urlstr); 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpResponse response = (HttpResponse) httpclient.execute(httpRequest); 

     HttpEntity entity = response.getEntity(); 
     BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); 
     is = bufHttpEntity.getContent(); 
     BitmapFactory.Options factoryOptions = new BitmapFactory.Options(); 
     bm = BitmapFactory.decodeStream(is); 
    }catch (MalformedURLException e){ 
     Log.d("RemoteImageHandler", "Invalid URL: " + urlstr); 
    }catch (IOException e){ 
     Log.d("RemoteImageHandler", "IO exception: " + e); 
    }finally{ 
     if(is!=null)try{ 
      is.close(); 
     }catch(IOException e){} 
    } 
    return bm; 
} 

我得到这个错误: -

D/skia(4965): --- SkImageDecoder::Factory returned null 

我已经尝试了各种组合的建议herehere等几种解决方案,但它不为我工作。我错过了什么吗?图片绝对存在于我输入的网址中。

谢谢。

回答

0

问题是无法下载图像,因为保存图像的目录没有“执行”权限。一旦权限被添加,该应用程序工作顺利:)

0

使用下面的代码下载图像并存储到位图中,它可能会帮助你。

public static Bitmap loadBitmap(String url) { 
    Bitmap bitmap = null; 
    InputStream in = null; 
    BufferedOutputStream out = null; 

    try { 
     in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE); 

     final ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 
     out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE); 
     out.flush(); 

     final byte[] data = dataStream.toByteArray(); 
     BitmapFactory.Options options = new BitmapFactory.Options(); 

     bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options); 
    } catch (IOException e) { 
     Log.e(TAG, "Could not load Bitmap from: " + url); 
    } finally { 
     closeStream(in); 
     closeStream(out); 
    } 

    return bitmap; 
} 
+0

什么是IO_BUFFER_SIZE? closeStream()是否简单地关闭连接? – gkris 2012-07-27 06:12:38

+0

什么是副本()? – gkris 2012-07-27 06:20:41

+0

声明私有静态final int IO_BUFFER_SIZE = 4 * 1024;这是缓冲区的大小并删除co​​py()。 – 2012-07-27 06:21:17