这是我做项目使用图片压缩最常用的类,现在分享出来给大家。
/**
* Created by Administrator on 2015/1/22 0022.
*/
public class ImageUtils {
/**
* 图片等比例缩放
* @param b
* @param x
* @param y
* @return
*/
public static Bitmap getBitMap(Bitmap b,float x,float y){
int w=b.getWidth();
int h=b.getHeight();
float sx=x/w;//图片缩放比例
float sy=y/h;
Matrix matrix = new Matrix();
matrix.postScale(sx, sy); // 设置缩放比例
Bitmap resizeBmp = Bitmap.createBitmap(b, 0, 0, w,
h, matrix, true);
return resizeBmp;
}
/**
* 正方形居中切法
* @param b 原图bitmap
* @return
*/
public static Bitmap getBitMap(Bitmap b){
int oldwidth = b.getWidth();
int oldheight = b.getHeight();
int newwidth = 0;
int newheight = 0;
int newx = 0;
int newy = 0;
if(oldwidth == oldheight){
newwidth = oldwidth;
newheight = oldwidth;
}else if(oldwidth > oldheight){
newx = (oldwidth - oldheight) / 2;
newheight = oldheight;
newwidth = oldheight;
}else if(oldwidth < oldheight){
newy = (oldheight - oldwidth) / 2;
newheight = oldwidth;
newwidth = oldwidth;
}else{
newwidth = oldwidth;
newheight = oldheight;
}
Bitmap bitmap = Bitmap.createBitmap(b,newx,newy,newwidth,newheight);
return bitmap;
}
public static int getWidthForPhone(WindowManager wm){
DisplayMetrics DM = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(DM);
return DM.widthPixels;
}
public static int getHeightForPhone(WindowManager wm){
DisplayMetrics DM = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(DM);
return DM.heightPixels;
}
public static Bitmap setImagePostion(WindowManager wm,Resources res,int imgId){
int windowWidth = getWidthForPhone(wm);
Bitmap bitmap = BitmapFactory.decodeResource(res, imgId);
int height = bitmap.getHeight() * windowWidth / bitmap.getWidth();
Bitmap bm = ImageUtils.getBitMap(bitmap, windowWidth, height);
return bm;
}
public static Bitmap setImagePostion(WindowManager wm,Bitmap bitmap){
int windowWidth = getWidthForPhone(wm);
int height = bitmap.getHeight() * windowWidth / bitmap.getWidth();
Bitmap bm = ImageUtils.getBitMap(bitmap, windowWidth, height);
return bm;
}
}
技术源于分享!!!!!