Android實現對圖片的縮放、剪下、旋轉、儲存

來源:互聯網
上載者:User

標籤:

一、問題描述

  在開發中,當我們需要的有一張大圖片同時還需要一些小圖片時,我們只需要通過代碼對此圖片進行不同比例的縮放即可,這樣大大節約資源,減小了安裝包的尺寸 。除縮放外,我們還經常對圖片進行其他動作如裁剪、旋轉、儲存等。

  這樣我們可以編寫對於圖片進行處理的萬用群組件,方便開發。下面就分享一下對圖片進行處理的組件BitmapUtil,案例介面:

二、技術點描述

  1、通過BitmapFactory取得Bitmap

Bitmap bm=BitmapFactory.decodeStream(InputStream is );

  2、Bimap的createBitmap()方法

Bitmap newbm = Bitmap.createBitmap( Bitmap s, int x, int y, int w, int h, Matrix m, boolean f);

  該方法可實現位元影像的縮放、裁剪、旋轉操作

  參數說明:

Bitmap s:要處理的原始位元影像

int x ,y:起始位置座標

int w:要截的圖的寬度

int h:要截的圖的寬度

Matrix m 矩陣,主要是用於平面的縮放、平移、旋轉

boolean f:是否保證等比

返回值:返回處理後的Bitmap

三、BitmapUtil組件

  可實現對圖片進行按比例縮放、圖片按比例裁剪、圓形圖片處理等方法,實現功能如下:

1、readBitmapById()方法
/**     * 通過資源id轉化成Bitmap     * @param context     * @param resId     * @return     */    public static Bitmap readBitmapById(Context context, int resId){        BitmapFactory.Options opt = new BitmapFactory.Options();        opt.inPreferredConfig = Bitmap.Config.RGB_565;        opt.inPurgeable = true;        opt.inInputShareable = true;        InputStream is = context.getResources().openRawResource(resId);        return BitmapFactory.decodeStream(is, null, opt);    }
2、scaleImage()方法,實現按指定寬高縮放圖片

  執行效果

/*** 縮放圖片     * @param bm 要縮放圖片     * @param newWidth 寬度     * @param newHeight 高度     * @return處理後的圖片     */    public static  Bitmap  scaleImage(Bitmap bm, int newWidth, int newHeight){        if (bm == null){            return null;        }        int width = bm.getWidth();        int height = bm.getHeight();        float scaleWidth = ((float) newWidth) / width;        float scaleHeight = ((float) newHeight) / height;        Matrix matrix = new Matrix();        matrix.postScale(scaleWidth, scaleHeight);        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,true);        if (bm != null & !bm.isRecycled()){            bm.recycle();//銷毀原圖片            bm = null;        }        return newbm;    }
3、imageCrop()方法

 執行效果

/**     * 按照一定的寬高比例裁剪圖片     * @param bitmap 要裁剪的圖片     * @param num1 長邊的比例     * @param num2 短邊的比例     * @param isRecycled是否回收原圖片     * @return 裁剪後的圖片     */    public static Bitmap  imageCrop(Bitmap bitmap, int num1, int num2, boolean isRecycled){        if (bitmap == null){            return null;        }        int w = bitmap.getWidth(); // 得到圖片的寬,高        int h = bitmap.getHeight();        int retX, retY;        int nw, nh;        if (w > h){            if (h > w * num2 / num1){                nw = w;                nh = w * num2 / num1;                retX = 0;                retY = (h - nh) / 2;            } else{                nw = h * num1 / num2;                nh = h;                retX = (w - nw) / 2;                retY = 0;            }        } else{            if (w > h * num2 / num1){                nh = h;                nw = h * num2 / num1;                retY = 0;                retX = (w - nw) / 2;            } else{                nh = w * num1 / num2;                nw = w;                retY = (h - nh) / 2;                retX = 0;}        }        Bitmap bmp = Bitmap.createBitmap(bitmap, retX, retY, nw, nh, null,false);        if (isRecycled && bitmap != null && !bitmap.equals(bmp)&& !bitmap.isRecycled()){            bitmap.recycle();//回收原圖片            bitmap = null;        }        return bmp;    }
4、toRoundCorner()實現將圖片轉圓角

   執行效果

 

/**     *圖片轉圓角      * @param bitmap需要轉的bitmap     * @param pixels轉圓角的弧度     * @return 轉圓角的bitmap     */    public static Bitmap toRoundCorner(Bitmap bitmap, int pixels)    {        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),                bitmap.getHeight(), Config.ARGB_8888);        Canvas canvas = new Canvas(output);        final int color = 0xff424242;        final Paint paint = new Paint();        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());        final RectF rectF = new RectF(rect);        final float roundPx = pixels;        paint.setAntiAlias(true);        canvas.drawARGB(0, 0, 0, 0);        paint.setColor(color);        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));        canvas.drawBitmap(bitmap, rect, rect, paint);        if (bitmap != null && !bitmap.isRecycled())        {            bitmap.recycle();        }        return output;    }
5、toRoundBitmap()方法將映像裁剪成圓形

   執行效果

public static Bitmap toRoundBitmap(Bitmap bitmap){if (bitmap == null){            return null;        }        int width = bitmap.getWidth();        int height = bitmap.getHeight();        float roundPx;        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;        if (width <= height){            roundPx = width / 2;            top = 0;            bottom = width;            left = 0;            right = width;            height = width;            dst_left = 0;            dst_top = 0;            dst_right = width;            dst_bottom = width;        } else{            roundPx = height / 2;            float clip = (width - height) / 2;            left = clip;            right = width - clip;            top = 0;            bottom = height;            width = height;            dst_left = 0;            dst_top = 0;            dst_right = height;            dst_bottom = height;        }        Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);        Canvas canvas = new Canvas(output);        final int color = 0xff424242;        final Paint paint = new Paint();        final Rect src = new Rect((int) left, (int) top, (int) right,                (int) bottom);        final Rect dst = new Rect((int) dst_left, (int) dst_top,                (int) dst_right, (int) dst_bottom);        final RectF rectF = new RectF(dst);        paint.setAntiAlias(true);        canvas.drawARGB(0, 0, 0, 0);        paint.setColor(color);        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));        canvas.drawBitmap(bitmap, src, dst, paint);        if (bitmap != null && !bitmap.isRecycled()){            bitmap.recycle();            bitmap = null;        }        return output;    }
6、rotaingImageView()方法,實現旋轉圖片

 執行效果

/**     * 旋轉圖片     * @param angle 旋轉角度     * @param bitmap 要處理的Bitmap     * @return 處理後的Bitmap     */    public static Bitmap rotaingImageView(int angle, Bitmap bitmap)    {        // 旋轉圖片 動作        Matrix matrix = new Matrix();        matrix.postRotate(angle);        // 建立新的圖片        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,                bitmap.getWidth(), bitmap.getHeight(), matrix, true);        if (resizedBitmap != bitmap && bitmap != null && !bitmap.isRecycled()){            bitmap.recycle();            bitmap = null;        }        return resizedBitmap;        }
7、saveBmpToSd()實現將儲存Bitmap到sdcard
       public static boolean saveBmpToSd(String dir, Bitmap bm, String filename,            int quantity, boolean recyle) {        boolean ret = true;        if (bm == null) {            return false;}        File dirPath = new File(dir);        if (!exists(dir)) {            dirPath.mkdirs();        }        if (!dir.endsWith(File.separator)) {            dir += File.separator;        }        File file = new File(dir + filename);        OutputStream outStream = null;        try {            file.createNewFile();            outStream = new FileOutputStream(file);            bm.compress(Bitmap.CompressFormat.JPEG, quantity, outStream);        } catch (Exception e) {            e.printStackTrace();            ret = false;        } finally {            try {                if (outStream != null) outStream.close();            } catch (IOException e) {                e.printStackTrace();            }            if (recyle && !bm.isRecycled()) {                bm.recycle();                bm = null;            }        }        return ret;    }

 

Android實現對圖片的縮放、剪下、旋轉、儲存

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.