我有一个Android应用程序可以将多个图像从mysql数据库加载到ImageButton。
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
我已经按照建议的here,here和其他几种解决方案尝试了各种组合,但它对我不起作用。我错过了什么吗?图像肯定存在于我输入的网址中。
谢谢。
答案 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;
}
答案 1 :(得分:0)
问题是无法下载图像,因为保存图像的目录没有“执行”权限。添加权限后,应用程序就会顺利运行:)