package com.bawei.yuezkao1.model.http;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.widget.ImageView;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
-
项目名称:图片工具类
-
@Author
-
创建时间:
*/
public class ImageUtils {//TODO 1, 单例
private static ImageUtils imageUtils = null;
private ImageUtils(){}
public static ImageUtils getImageUtils() {
if(imageUtils == null){
imageUtils = new ImageUtils();
}
return imageUtils;
}//TODO 2, 声明Handler对象
private Handler handler = new Handler();//TODO 3, 加载图片 — SD + 网络的缓存
public void loadImage(final String imagePath, final ImageView imageView){
//判断sd卡中是否有该图片
String fileName = imagePath.substring(imagePath.lastIndexOf("/")+1);
final File file = new File(Environment.getExternalStorageDirectory()+"/"+fileName);
if(file.exists()){
//获取并展示 – 图片的二次采样
Bitmap bitmap = scaleImage(file);
imageView.setImageBitmap(bitmap);
}else {
//开启线程下载图片
new Thread(){
@Override
public void run() {
super.run();
try {
URL url = new URL(imagePath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(“GET”);
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
if(connection.getResponseCode() == 200){
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bitmap = BitmapFactory.decodeStream(bis);
is.close();bis.close(); connection.disconnect();//关闭流//TODO 将获取到的bitmap图片,存入sd卡 bitmap.compress(Bitmap.CompressFormat.JPEG,100,new FileOutputStream(file)); //TODO 展示图片 -- 现在是在子线程中, 需要通过handler的post方式, 在主线程中展示图片 handler.post(new Runnable() { @Override public void run() { imageView.setImageBitmap(scaleImage(file)); } }); } } catch (Exception e) { e.printStackTrace(); } } }.start(); }
}
//TODO 4, 图片的二次采样
public Bitmap scaleImage(File file){
BitmapFactory.Options options = new BitmapFactory.Options();//得到参数对象
options.inSampleSize = 4;//压缩比例
options.inPreferredConfig = Bitmap.Config.RGB_565;//图片画质质量
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(),options);
return bitmap;
}
}