异步加载图片,存在sd卡缓存,比例设置图片

adapter:

 

public class PopFavourFoodAdapter extends BaseAdapter {

	..........

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.pop_favour_food_item, null);
		}

           int width = PublicUtil.getWidth(context)/2-40;//两列并减去40的间距
         int height= width*380/260;//图片的长哦380,宽为260
         LayoutParams lp = iv_image.getLayoutParams();
        lp.height= height;
        lp.width = width;
          iv_image.setLayoutParams(lp);
               String imgUrl = PublicVariable.webRoot +"/res/rst_photo_thumb/"+list.get(position).getPhoto(); 
		TextView  tv_cn_name = (TextView)convertView.findViewById(R.id.tv_cn_name);
		ImageView iv_image = (ImageView)convertView.findViewById(R.id.image);
		tv_cn_name.setText(list.get(position).getFoodName());
		iv_image.setTag(imgUrl );//设置一个标签
		new LoadingTopicImageAsyncTask(iv_image, (Activity) context,
				false, imgUrl ,"small").execute();
		return convertView;
	}
//屏幕的宽度
 public static int getWidth(Context context) {
  WindowManager wm = (WindowManager) context
    .getSystemService(Context.WINDOW_SERVICE);
  return wm.getDefaultDisplay().getWidth();
 }
 public static int getHeight(Context context) {
  WindowManager wm = (WindowManager) context
    .getSystemService(Context.WINDOW_SERVICE);
  return wm.getDefaultDisplay().getHeight();
 }

 LoadingTopicImageAsyncTask.java:

 

**
 * @name 异步加载图片
 * @author allen
 * @create_date 2012-10-18
 */
public class LoadingTopicImageAsyncTask extends
		AsyncTask<String, Integer, String> {
	private ImageView imageView = null;
	private Bitmap bt = null;
	private Activity activity;
	private boolean isClick = true;
	private String tag = "";
	private String type;

	public LoadingTopicImageAsyncTask(ImageView imageView, Activity activity,
			boolean isClick, String tag,String type) {
		super();
		this.imageView = imageView;
		this.activity = activity;
		this.isClick = isClick;
		this.tag = tag;
		this.type = type;
	}

	@Override
	protected String doInBackground(String... params) {
		// 添加如果是本地缓存的从本地读取
		SoftReference<Bitmap> softReference = PublicVariable.allTopicImage.get(tag);
		if(softReference!=null)
		bt = PublicVariable.allTopicImage.get(tag).get();
		if (bt == null) {
			// 图像获取并保存
			if (tag.endsWith("null")||tag == null || tag.equals("")) {
				bt = null;
			} else {
				bt = new PublicVariable ().ReturnBitMap(tag,type);
			}
		}
		
		return null;
	}

	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		if (imageView != null && !"".equals(tag)) {
			// Log.i("tag", tag);
			if (imageView.getTag() != null
					&& imageView.getTag().toString().equals(tag)) {
				if (bt != null) {
					if (isClick) {
						// 点击大图效果
						imageView.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								// ShowImageClickListener(bt, activity);
							}
						});
					}
					imageView.setImageBitmap(bt);
					PublicVariable.allTopicImage.put(tag,
							new SoftReference<Bitmap>(bt)); // 保存到数组中
				} else {
					imageView.setImageResource(R.drawable.nopic);
				}
			} else {
				imageView.setImageResource(R.drawable.nopic);
			}
		}
	}

	/**
	 * 图片点击功能事件处理
	 * 
	 * @parambt
	 * @paramactivity
	 */
	public void ShowImageClickListener(Bitmap bt, Activity activity) {
		
	}

}

 

 

 

public class PublicVariable {
	public static HashMap<String, SoftReference<Bitmap>> allTopicImage = new HashMap<String, SoftReference<Bitmap>>();

/**
	 * 返回图片文件用
	 * 
	 * @paramurl 图片url地址
	 * @return
	 */
	public Bitmap ReturnBitMap(String url,String type) {
		String imgName = getImageNameForUrl(url,type);
		if (imgName.equals("")) {
			return null;
		} else {
			// FileTool ft = new FileTool();
			String path = PublicUtil.getImagePath();
			File file = new File(path+imgName);
			// 图片文件存在并且不是刷新的时候
			if (file.exists()) {
				Bitmap bm = ReturnLocalBitMap(path + imgName);
				if (bm == null) {
					return ReturnWebBitMap(url, imgName, path);
				} else {
					return bm;
				}
				
			} else {
				// 先删除原有的
				return ReturnWebBitMap(url, imgName, path);
			}
		}
	}
       /**
         得到图片名字
     **/
	public static String getImageNameForUrl(String url,String type) {
		// TODO Auto-generated method stub
		String imageName = url.substring(url.lastIndexOf("/") + 1)+"."+type;
		return imageName;
	}
	/**
	 * 本地获取图片信息
	 * 
	 * @parampath 图片路径
	 * @return bitmap对象
	 */
	public Bitmap ReturnLocalBitMap(String path) {
		Bitmap bitmap = BitmapFactory.decodeFile(path);
		return bitmap;
	}

/**
	 * 抓取远程图片
	 * 
	 * @paramurl 图片地址
	 * @paramimgName 图片名
	 * @parampath 地址
	 * @return
	 */
	public Bitmap ReturnWebBitMap(String url, String imgName, String path) {

		Bitmap bitmap = null;
		try {
			// 图片大小判断操作
			InputStream size_is = getInputStream(url);
			BitmapFactory.Options op = new BitmapFactory.Options();
			op.inJustDecodeBounds =true;  
	        Bitmap size_bitmap =BitmapFactory.decodeStream(size_is, null, op);  
			op.inJustDecodeBounds = true; // 仅获取宽高信息,不加载整个图片
			boolean isop = false;
			int size = 800; // 设定获取的大小不能超过宽高
			int bili = 0; // 压缩比例
			BitmapFactory.Options op_new = new BitmapFactory.Options();
			if (op.outWidth > op.outHeight) {
				if (op.outWidth > size) {
					bili = op.outWidth / size;
					isop = true;
				}
			} else {
				if (op.outHeight > size) {
					bili = op.outHeight / size;
					isop = true;
				}
			}

			// 根据比例判断
			if (bili != 0) {
				if (bili < 2) {
					bili = 2;
				} else {
					bili = bili * 2 - 2;
				}
				if (bili % 2 != 0) {
					bili = bili + 1;
				}
				op_new.inSampleSize = bili;
			} else {
				isop = false;
			}
			System.out.println(bili);
			size_bitmap = null;
			size_is.close();

			// 如果进行过压缩,加载处理后的图片,如果没有直接加载
			InputStream is = AsyncImageLoader.getInputStream(url);
			if (isop) {
				op_new.inPreferredConfig = Bitmap.Config.ARGB_4444;
				op_new.inPurgeable = true;
				op_new.inInputShareable = true;
				bitmap = BitmapFactory.decodeStream(is, null, op_new);
			} else {
				bitmap = BitmapFactory.decodeStream(is);
			}
			is.close();

			// 将图片写入到内存卡中,做为缓存,将来直接本地读取
			WriteBitmapToSdCard(path, imgName, bitmap);
			return bitmap;


		} catch (Exception e) {
			return null;
		}
	}

  public InputStream getInputStream(String url) {
		// TODO Auto-generated method stub
		URL m;
		InputStream i = null;
		try {
			m = new URL(url);
			i = (InputStream) m.getContent();
			System.out.println("url=="+url);
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			System.out.println("error_url=="+url);
			e.printStackTrace();
		}
		return i;
	}
//将图片写入到内存卡中,做为缓存,将来直接本地读取
public static void WriteBitmapToSdCard(String path, String fileName,
			Bitmap bitmap) throws IOException {
		// TODO Auto-generated method stub
		File dirFile = new File(path);
		if (!dirFile.exists()) {
			dirFile.mkdir();
		}
		File myCaptureFile = new File(path + fileName);
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(myCaptureFile));
		bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
		bos.flush();
		bos.close();
	}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值