안드로이드 캡슐화 도구

10587 단어
현재 휴대전화 카메라가 찍은 사진은 이미 매우 커서 사진 처리를 하지 않고 직접 표시하지 않으면 프로그램이 oom이상일 수도 있다. 앞으로의 편의를 위해 매번 쓰지 않기 위해 이번에는 사진 처리에 자주 사용하는 방법을 한데 봉하여 나중에 사용하기 편리하게 한다.BitMapManager 클래스를 만들고 코드를 복사합니다.
package com.zydl.smartcityfuyang.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.media.ExifInterface;
import android.util.Log;

public class BitMapManager {

    public static byte[] lastPicByte; //           
    /**
     *            (  Bitmap    )
     * 
     * @param image
     * @return
     */
    public static Bitmap comp(Bitmap image) {
        Bitmap bitmap = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            if (baos.toByteArray().length / 1024 > 1024) {//         1M,           (BitmapFactory.decodeStream)   
                baos.reset();//    baos   baos
                image.compress(Bitmap.CompressFormat.JPEG, 60, baos);//      60%,          baos 
            }
            ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
            BitmapFactory.Options newOpts = new BitmapFactory.Options();
            //       
            newOpts.inJustDecodeBounds = true;
            bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
            newOpts.inJustDecodeBounds = false;
            int w = newOpts.outWidth;
            int h = newOpts.outHeight;
            //           800*480   ,          
            float hh = 800f;//         800f
            float ww = 480f;//        480f
            //    。         ,                  
            int be = 1;// be=1     
            if (w > h && w > ww) {//                  
                be = (int) (newOpts.outWidth / ww);
            } else if (w < h && h > hh) {//                  
                be = (int) (newOpts.outHeight / hh);
            }
            if (be <= 0)
                be = 1;
            newOpts.inSampleSize = be;//        
            //       ,       options.inJustDecodeBounds   false 
            isBm = new ByteArrayInputStream(baos.toByteArray());
            lastPicByte = baos.toByteArray();
            double lenth = lastPicByte.length / 1024;
            baos.close();
            bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
            isBm.close();
            return compressImage(bitmap);//               
        } catch (Exception e) {
            // TODO: handle exception
        }
        return bitmap;
    }

    /**
     *            (           
     * 
     * @param srcPath
     * @return
     */
    public static Bitmap compressImage(String srcPath) {
        Bitmap bitmap = null;
        try {
            BitmapFactory.Options newOpts = new BitmapFactory.Options();
            //       ,   options.inJustDecodeBounds   true 
            newOpts.inJustDecodeBounds = true;
            bitmap = BitmapFactory.decodeFile(srcPath, newOpts);//     bm  

            newOpts.inJustDecodeBounds = false;
            int w = newOpts.outWidth;
            int h = newOpts.outHeight;
            // //           800*480   ,          
            float hh = 800f;//        800f
            float ww = 480f;//        480f
            //    。         ,                  
            int be = 1;// be=1     
            if (w > h && w > ww) {//                  
                be = (int) (newOpts.outWidth / ww);
            } else if (w < h && h > hh) {//                  
                be = (int) (newOpts.outHeight / hh);
            }
            if (be <= 0)
                be = 1;
            newOpts.inSampleSize = be;//       
            //       ,       options.inJustDecodeBounds   false 
            bitmap = BitmapFactory.decodeFile(srcPath, newOpts);

            /**
             *    Android  ( MT788、Note2) ,  Camera    ,           (90°、180°、
             * 270° ),          ,       
             */
            int degree = getBitmapDegree(srcPath);
            int roateDegree = 180 - degree;
            if (degree != 0) {
                bitmap = rotateBitmapByDegree(bitmap, roateDegree);
            }
            return compressImage(bitmap);//                
        } catch (Exception e) {
            // TODO: handle exception
        }
        return bitmap;
    }

    /**
     *        
     */
    public static Bitmap compressImage(Bitmap image) {
        Bitmap bitmap = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//       ,  100     ,          baos 
            int options = 100;
            while (baos.toByteArray().length / 1024 > 50) { //                10kb,      
                baos.reset();//   baos   baos
                options -= 10;//      10
                image.compress(Bitmap.CompressFormat.JPEG, options, baos);//     options%,          baos 

            }
            ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//        baos   ByteArrayInputStream 
            //    

            lastPicByte = baos.toByteArray();
            double lenth = lastPicByte.length / 1024;
            Log.e("jinli", "      :" + lenth + "kb");
            baos.close();

            bitmap = BitmapFactory.decodeStream(isBm, null, null);//  ByteArrayInputStream      
            isBm.close();

            //              90 
            // bitmap = rotateBitmapByDegree(bitmap, 90);
            return bitmap;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     *           
     *
     * @param path
     *                  
     * @return        
     */
    public static int getBitmapDegree(String path) {
        int degree = 0;
        try {
            //           ,    EXIF  
            ExifInterface exifInterface = new ExifInterface(path);
            //          
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                // case ExifInterface.ORIENTATION_NORMAL:
                // degree = -90;
                // break;
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     *              
     *
     * @param bm
     *                   
     * @param degree
     *                
     * @return       
     */
    public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
        Bitmap returnBm = null;

        //       ,      
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            //                ,       
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }

    /**
     *        
     *
     * @param bitmap
     *              Bitmap  
     * @return
     */
    public static Bitmap toRoundBitmap(Bitmap bitmap) {
        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;
            left = 0;
            top = 0;
            right = width;
            bottom = 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); //     Canvas
        paint.setColor(color);

        //          ,drawRounRect drawCircle
        // canvas.drawRoundRect(rectF, roundPx, roundPx, paint);//
        //      ,            ,                           。
        canvas.drawCircle(roundPx, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));//             ,  http://trylovecatch.iteye.com/blog/1189452
        canvas.drawBitmap(bitmap, src, dst, paint); //  Mode.SRC_IN    bitmap   draw  Circle

        return output;
    }

    public static Bitmap toOvalBitmap(Bitmap bitmap) {

        Bitmap output = Bitmap.createBitmap(bitmap.getHeight(), bitmap.getWidth(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        Paint paint = new Paint();
        Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        RectF rectF = new RectF(rect);

        canvas.drawOval(rectF, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rectF, paint);
        return output;
    }

}

좋은 웹페이지 즐겨찾기