2015年4月20日 星期一

【Android】 Bitmap To Bitmap 縮圖
















轉載  http://spadesa.blogspot.tw/2013/05/android.html






    private Bitmap reBitmapSize(Bitmap bit, int MaxPx) {

        int width = bit.getWidth(), height = bit.getHeight();

        if (width < MaxPx && height < MaxPx) {

            return bit;// 傳進來的圖比要的小,不處理
        }

        float ratio = 1;// 縮放比例

        if (width > height && width > MaxPx) {

            //這張圖比較寬,依寬度進行等比例縮放
            ratio = (float)MaxPx / (float)width;

        } else if (height > MaxPx) {

            //這張圖比較高,依高度進行等比例縮放
            ratio = (float)MaxPx / (float)height;
        }



        if (ratio >= 1) {

            //如果比例不需要縮小,返回原圖,如果你有放大需求,可以修改這邊
            return bit;

        } else {

            int newW=(int)(width * ratio),newH=(int) (height * ratio);

            if(newW<=0 || newH<=0){

                if (width > height && width > MaxPx) {

                    ratio = (float)1024.0 / (float)width;

                } else if (height > MaxPx) {

                    ratio = (float)1024.0 / (float)height;

                }

                newW=(int)(width * ratio);

                newH=(int) (height * ratio);

            }

            Bitmap marker = Bitmap.createBitmap(newW, newH, Bitmap.Config.ARGB_8888);

            Canvas canvas = new Canvas(marker);

            try {

                canvas.drawBitmap(bit, new Rect(0, 0, width, height), new Rect(0, 0, newW, newH), null);

            } catch (Exception e) {}

            // return new BitmapDrawable(marker); //如果你需要的是Drawable 用這行
            return marker;

        }

    }

沒有留言:

張貼留言