zoukankan      html  css  js  c++  java
  • 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;
    	}
    
  • 相关阅读:
    2019课设---基于微信小程序的食堂订餐送餐系统设计 【构思】(12)
    宝塔安装
    win10添加新建文本文档的快捷方式
    Vue底部菜单模块
    CSS渐变
    记录页面位置及进入页面时跳转位置
    PHP获取微信JS-SDK接口设置(access_token、jsapi_ticket、signature)
    添加Notepad++至右键菜单
    win10卸载XShell6报错1603
    win10我的电脑左侧快捷方式的控制
  • 原文地址:https://www.cnblogs.com/budoudou/p/2105025.html
Copyright © 2011-2022 走看看