图片二次采样

public class MainActivity extends AppCompatActivity {

    private ImageView imageView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.btn_down);
        imageView = (ImageView) findViewById(R.id.img);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //加载一张大图时,显示不出来,需要进行二次采样
                new MyPicTask().execute("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1507587322735&di=f9178e70b29b4d4f3f99244700064d99&imgtype=0&src=http%3A%2F%2Fattachments.gfan.com%2Fforum%2F201606%2F24%2F2340578lqll23i231cn3i4.jpg");

            }
        });

    }



    /**
     * 使用异步任务请求图片
     */
    class MyPicTask extends AsyncTask<String, Void, Bitmap> {

        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap bitmap = null;
            try {
                //1.创建url对象
                URL url = new URL(params[0]);
                //2.打开连接
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                //3.设置
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(5000);
                connection.setConnectTimeout(5000);
                //4.得到结果码,并且判断
                int code = connection.getResponseCode();
                if (code == 200) {
                    //5.得到结果
                    InputStream inputStream = connection.getInputStream();
                    //将流转换成Bitmap对象
//                    bitmap = BitmapFactory.decodeStream(inputStream);
                    bitmap=commpressPic(inputStream,320,320);

                }
            } catch (Exception e) {
                e.printStackTrace();
                if(e!=null){
                    Log.e("zzz",e.getMessage().toString());
                }

            }


            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            //显示图片
            imageView.setImageBitmap(bitmap);

        }
    }

    //图片的二次采样
    //1.原因:加载大质量图片时,为了避免OOM(内存溢出)异常
    //2.是什么? 对图片进行压缩
    //3.如何进行压缩? BitmapFactory  BitmapFactory.Options
    public Bitmap commpressPic(InputStream inputStream, int targetWidthPx, int targetHeightPx) {
        Bitmap result=null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        //设置为true,只取得宽度与高度的数据,只加载边框
        options.inJustDecodeBounds=true;

        try {
            byte[] data=inputStream2ByteArr(inputStream);
            //进行转换
//        Bitmap bitmap=BitmapFactory.decodeStream(inputStream,null,options);
            Bitmap bitmap=BitmapFactory.decodeByteArray(data,0,data.length,options);
            Log.d("zzz","bitmap:"+bitmap);

            int picHeight=options.outHeight;
            int picWidth=options.outWidth;
            Log.d("zzz","图片实际的高度(px):"+picHeight+" 图片实际的宽度(px):"+picWidth);
            /////////////////////第一次采样完成(只加载图片的边框进来,获取图片实际的宽度与高度)////////////////////////////////////////////////////////
            //2500x1600  实际宽度与高度

            //320x320 目标宽度与高度
            //计算缩放比率
            int simpleSize=1;
            if(picHeight>targetHeightPx || picWidth>targetWidthPx){

                int heightRate=picHeight/targetHeightPx;
                int widthRate=picWidth/targetWidthPx;

                Log.d("zzz","heightRate:"+heightRate+" widthRate:"+widthRate);
                //选取两者之间最小的
                simpleSize=heightRate<widthRate?heightRate:widthRate;

                Log.d("zzz","simpleSize:"+simpleSize);
            }

            options.inSampleSize=simpleSize;//缩放比率 2  宽度压缩到1/2 高度压缩1/2    =====1/4
            options.inJustDecodeBounds=false;//加载实际的图片质量
            //设置图片色彩模式  rgb_565 一个像素在内存占两个字节   rgb_8888 一个像素在内存占四个字节
            options.inPreferredConfig= Bitmap.Config.RGB_565;


            //原因是decodeStream不能重复解析同一个网络流的inputStream
//        result=BitmapFactory.decodeStream(inputStream,null,options);
            result=BitmapFactory.decodeByteArray(data,0,data.length,options);
            Log.d("zzz","result:"+result);
            ////////////第二次采样结束(计算图片的压缩比率)/////////////////////////////////////////////////////////////////////
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private byte[] inputStream2ByteArr(InputStream inputStream) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len = 0;
        while ( (len = inputStream.read(buff)) != -1) {
            outputStream.write(buff, 0, len);
        }
        inputStream.close();
        outputStream.close();
        return outputStream.toByteArray();
    }

}
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页