Android如何从网络中获取图片
android中内置apache,可以通过该组件从网络中获取相关的资源,图片也是一种资源,在图片
获取中应该注意二点:
1. 最好使用Buffered***,因为这样的话数据不是一个一个字节这样读取,而读了一段数据后,放在一个内存中,然后在从内存中拿,这样
会比较快
2. 如果图片url 中含有中文字符,需要encode url,因为很多服务器中文字符是不认识的。
imageUrl = imagePrefix + URLEncoder.encode(imageName, "utf-8");
public static synchronized Bitmap getOnlineBookIcon(String imageUrl, String contentId) {
Bitmap bitmap = null;
URL url = null;
FileOutputStream bos = null;
File imageFile = null;
byte[] bytes = null;
BufferedInputStream bis = null;
System.out.println("imageUrl" + imageUrl);
System.out.println("contentId" + contentId);
try {
if (validateImageURL(imageUrl)) {
String imagePrefix = imageUrl.substring(0, imageUrl.lastIndexOf("/") + 1);
String imageName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1, imageUrl.length());
String imagePath = composeOnlineImagePath(contentId);
imageFile = new File(imagePath);
if (imageFile.exists() && imageFile.length() > 0) {
bitmap = BitmapFactory.decodeFile(imagePath);
} else {
checkImageSize();
imageUrl = imagePrefix + URLEncoder.encode(imageName, "utf-8");
url = new URL(CoverImageUtil.replaceWhiteSpaces(imageUrl));
bis = new BufferedInputStream(url.openStream());
bytes = new byte[2048];
bos = new FileOutputStream(imageFile);
int len;
while ((len = bis.read(bytes)) >= 0) {
bos.write(bytes, 0, len);
}
bis.close();
bos.flush();
bos.close();
bitmap = BitmapFactory.decodeFile(imagePath);
}
}
} catch (Exception e) {
if (imageFile != null)
imageFile.delete();
e.printStackTrace();
}
finally {
url = null;
bytes = null;
if (bitmap == null)
bitmap = getBookIcon(contentId);
}
return bitmap;
}
浙公网安备 33010602011771号