Android Studio 原生图片工具类(二次采样)

图片工具类(二次采样)
private static ImageUtils imageUtils = null;
private ImageUtils(){}

public static ImageUtils getImageUtils() {
    if (imageUtils == null){
        imageUtils = new ImageUtils();
    }
    return imageUtils;
}

private Handler handler = new Handler();

//封装图片异步加载框架,完成广场列表图片显示
public void loadImage(final String imagePath, final ImageView imageView){
    new Thread(){
        @Override
        public void run() {
            super.run();
            //获取图片文件名称
            String fileName = imagePath.substring(imagePath.lastIndexOf("/")+1);
            //获取图片路径
            final File file = new File(Environment.getExternalStorageDirectory() + "/" + fileName);
            //判断SD卡是否存在图片
            if (file.exists()){
                imageView.setImageBitmap(scalrImage(file));
            }else{
                try {
                    URL url = new URL(imagePath);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(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();

                        //将在图片异步加载框架中把加载过的图片缓存到SD卡中
                        bitmap.compress(Bitmap.CompressFormat.JPEG,100,new FileOutputStream(file));

                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                imageView.setImageBitmap(scalrImage(file));
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }.start();
}

//在图片异步加载框架中使用二次采样
public Bitmap scalrImage(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;
}

你可能感兴趣的:(图片二次采样,bitmap)