Bitmap 工具类

来源:互联网 发布:折扣算法 编辑:程序博客网 时间:2024/05/17 23:22
package com.quanju.mycircle.util;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


public class CreatBmp {
/**
* 截取图片中间部分
* @param bmp
* @return
*/
public static Bitmap creatbmp(Bitmap bmp){
int width = bmp.getWidth();
int height = bmp.getHeight();
int x,y;
if(width>height){
x = (width - height)/2;
y = 0;
width = height;
}else{
x = 0;
y = (height -width)/2;
height = width;
}
Bitmap tbmp = Bitmap.createBitmap(bmp, x, y, width, height);
return tbmp;
}

/**
* 保持图片到相册
* @param bitmap
* @return
*/
public static boolean dosave(Bitmap bitmap){
String filename = (new java.util.Date().getTime()/1000)+".jpg";
String sdpath = android.os.Environment
.getExternalStorageDirectory().toString();

File bitmapFile = new File(sdpath + "/DCIM/MyCircle/" + filename);
FileOutputStream fOut = null;
try {
File file = new File(sdpath + "/DCIM/MyCircle/");
if (!file.exists()) {
file.mkdirs();
}
bitmapFile.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return false;
}
try {
fOut = new FileOutputStream(bitmapFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
bitmap.compress(CompressFormat.JPEG, 100, fOut);
try {
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
return false;
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;

}
/**
* 检查图片是否已被旋转,如果被旋转则纠正
* @param bmp
* @param picpath
* @return
*/
public static Bitmap rotateBitmap(Bitmap bmp,String picpath){
ExifInterface exif;
try {
exif = new ExifInterface(picpath);
String oraentation = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
if(oraentation != null && oraentation.equals("6")){
Matrix matrix = new Matrix();  
//  将图像顺时针旋转90度  
matrix.setRotate(90);  
//  生成旋转后的图像  
return Bitmap.createBitmap(bmp, 0, 0,  
bmp.getWidth(), bmp.getHeight(), matrix, false);


}else if(oraentation != null && oraentation.equals("8")){
Matrix matrix = new Matrix();  
//  将图像顺时针旋转90度
matrix.setRotate(-90);  
//  生成旋转后的图像  
return Bitmap.createBitmap(bmp, 0, 0,  
bmp.getWidth(), bmp.getHeight(), matrix, false);  

}else{
return bmp;
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return bmp;
} catch (OutOfMemoryError e) {
e.printStackTrace();
return bmp;
}

}




    /**

* 保持图片到相册
* @param context
     * @param url
*/  
public void doSave(final String url,final  Context context){
final  ProgressDialog pb = new ProgressDialog(context);
pb.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pb.setMessage("正在保存");
pb.show();
final Handler handler = new Handler(){


@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0://保存成功
                    pb.dismiss();
                    Toast.makeText(context,"保存成功",Toast.LENGTH_SHORT).show();
break;
case 1://保持失败
pb.dismiss();
                    Toast.makeText(context,"保存失败",Toast.LENGTH_SHORT).show();
break;
default:
break;
}
super.handleMessage(msg);
}

};


        String filename = (new java.util.Date().getTime()/1000)+".jpg";
        String sdpath = android.os.Environment
                .getExternalStorageDirectory().toString();


        File saveFile = new File(sdpath + "/DCIM/MyCircle/" + filename);
        try {
            File file = new File(sdpath + "/DCIM/MyCircle/");
            if (!file.exists()) {
                file.mkdirs();
            }
            saveFile.createNewFile();
        } catch (IOException e1) {
            e1.printStackTrace();
            handler.sendEmptyMessage(1);
            return;
        }
        if(url!=null &&!url.equals(""))
        {
            new downloadTask(url,5,sdpath + "/DCIM/MyCircle/" + filename,handler).start();
        } else {
            handler.sendEmptyMessage(1);
        }


}


public static Bitmap zoomBitmap(String path,int SampleSize) {
Bitmap bmp = null;
try{
BitmapFactory.Options opt = new BitmapFactory.Options(); 
opt.inSampleSize = SampleSize;
bmp = BitmapFactory.decodeFile(path, opt);
}catch(OutOfMemoryError e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
return bmp;

}


    /**
     *
     * @param path
     * @param maxWidth
     * @param maxHeight
     * @return
     */
    //先取出图片的宽和高,然后在取出实际返回图片
    public  Bitmap  fitMaxBitMap(String path,int maxWidth,int maxHeight)
    {
        Bitmap bmp = null;
        int realWidth =0;
        int realHeight =0;


        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bmtWH = BitmapFactory.decodeFile(path, options);


        realWidth = options.outWidth;
        realHeight = options.outHeight;



        int fitSize =0;
        float scale =0f;


        //返回图片的实际宽和高
        int bitMapWidth =0;
        int bitMapHeight =0;
        int SampleSize = 1;


        if(realWidth>=realHeight) //以高为基准
        {
            fitSize = realHeight;


            //保持等比缩放
            bitMapHeight = fitSize;
            bitMapWidth = realWidth;


            if(bitMapHeight>maxHeight) //再次压缩,到固定大小
            {
               scale = (float)maxHeight/bitMapHeight;   //必须强制转,否则会当整数
               bitMapHeight = maxHeight;
               bitMapWidth =(int) (bitMapWidth*scale);
               fitSize = maxHeight;
               SampleSize = realHeight/fitSize ;
               if(realHeight%fitSize !=0)
               {
                   SampleSize+=1;
               }
                if(SampleSize%2!=0) //调试发现SampleSize只有偶数才起作用,为了不超过最大maxwidth和maxheight
                {
                    SampleSize+=1;
                }
//                Log.e("fitSize: ",fitSize+": "+realHeight+" :"+SampleSize) ;
            }


        } else //以宽为基准
        {
            fitSize = realWidth;




            bitMapWidth = fitSize;
            bitMapHeight = realHeight;


            if(bitMapWidth>maxWidth)
            {
                scale = (float) maxWidth/bitMapWidth;
                bitMapWidth = maxWidth;
                bitMapHeight = (int)(bitMapHeight * scale);  //必须强制转,否则会当整数
                fitSize = maxWidth;
                SampleSize = realWidth/fitSize;
                if(realWidth%fitSize !=0)
                {
                    SampleSize+=1;
                }
                if(SampleSize%2!=0) //调试发现SampleSize只有偶数才起作用,为了不超过最大maxwidth和maxheight
                {
                    SampleSize+=1;
                }
//              Log.e("fitSize: ",fitSize+": "+realWidth+" :"+SampleSize) ;
            }
        }




        //重新构建
        options.outWidth = bitMapWidth;
        options.outHeight = bitMapHeight;
        /* 这样才能真正的返回一个Bitmap给你 */
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;


        options.inSampleSize = SampleSize;
        options.inPurgeable = true;
        options.inInputShareable = true;


        bmp = BitmapFactory.decodeFile(path, options);
//        Log.e("bmpsize", bmp.getHeight() + ":" + bmp.getWidth());


        return bmp;
    }




    /**
     * 图片旋转
     *
     * @param bitmap
     * @param rotation
     *            旋转的角度
     */
    public static Bitmap rotation(Bitmap bitmap, int rotation) {
        Matrix matrix = new Matrix();
        matrix.setRotate(rotation);
        Bitmap tempBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, false);
//        if(!bitmap.isRecycled())
//        {
//            bitmap.recycle();
//            bitmap = null;
//        }
        return tempBitmap;
    }
}