android上的图片缩放处理
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.Log;
public class PhotoCompressUtils {
/**
* 缩放图片,返回一个byte
*
* @param filePath
* 文件路径
* @param width
* 宽度
* @param height
* 高度
* @return 一个图片数组
* @throws Exception
*/
public static byte[] compress(String filePath, int width, int height)
throws Exception {
Bitmap bm = CreatImage(filePath);
if (bm.getWidth() < width || bm.getHeight() < height) {
Log.e("Image", "file size not have the format!!");
return null;
}
bm = zoomImage(bm, 200, 200);
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
return out.toByteArray();
}
/**
* 图片处理
*
* @param bgimage
* @param newWidth
* @param newHeight
* @return
*/
public static Bitmap zoomImage(Bitmap bgimage, int newWidth, int newHeight) {
// 获取这个图片的宽和高
int width = bgimage.getWidth();
int height = bgimage.getHeight();
// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
// 计算缩放率,新尺寸除原始尺寸
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 缩放图片动作
matrix.postScale(scaleWidth, scaleHeight);
Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, width, height,
matrix, true);
return bitmap;
}
/*
* 获得图片
*/
public final static Bitmap CreatImage(String pathName) {
Bitmap bitmaptemp = null;
bitmaptemp = BitmapFactory.decodeFile(pathName);
return bitmaptemp;
}
}