1. 程式人生 > >筆記:Android不失真壓縮圖片

筆記:Android不失真壓縮圖片

        String imagePath = getIntent().getStringExtra("bitmap_uri");
        Display dis = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        dis.getSize(size);
        int windowWidth = size.x;
        int windowHeight = size.y;
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imagePath, opts);
        int bitmapHeight = opts.outHeight;
        int bitmapWidth = opts.outWidth;
        if (bitmapHeight > windowHeight || bitmapWidth > windowWidth) {
            int scaleX = bitmapWidth/windowWidth;
            int scaleY = bitmapHeight/windowHeight;
            if(scaleX>scaleY){//按照水平方向的比例縮放
                opts.inSampleSize = scaleX;
            }else{//按照豎直方向的比例縮放
                opts.inSampleSize = scaleY;
            }

        }else{//如果圖片比手機螢幕小 不去縮放了.
            opts.inSampleSize = 1;
        }
        //讓點陣圖工廠真正的去解析圖片
        opts.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath, opts);
        clipLayout.setImageSource(bitmap);