图片缩放中常用的有:
1.BitmapFactory.Options
eg:// 特点:图片原始尺寸的固定比例缩小(不能进行放大)
public Bitmap optionCompressBitmap(int drawableId, int destWidth,
int destHeight) {
// 获取原始图片的尺寸
BitmapFactory.Options srcOption = new BitmapFactory.Options();
srcOption.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), drawableId, srcOption);
int srcWidth = srcOption.outWidth;
int srcHeight = srcOption.outHeight;
int scale = (int) Math.max((srcWidth / destWidth),
(srcHeight / destHeight));
// 修改原始图片的option
srcOption.inSampleSize = scale;
srcOption.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(getResources(), drawableId,
srcOption);
}
2.Matrix
eg:// matrix:缩放非常灵活(如果需要不按照原始比例,这个是非常恰当的) 当图片所在的资源文件夹与手机的不对应,会出现奇葩的现象
public Bitmap matrixCompressBitmap(int drawableId, int destWidth,
int destHeight) {
// 获取原始图片的尺寸
BitmapFactory.Options srcOption = new BitmapFactory.Options();
srcOption.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), drawableId, srcOption);
int srcWidth = srcOption.outWidth;
int srcHeight = srcOption.outHeight;
float scaleWidth = destWidth / srcWidth;
float scaleHeight = destHeight / srcHeight;
// 修改原始图片的缩放比
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap srcBitmap = BitmapFactory.decodeResource(getResources(),
drawableId);
Bitmap bitmap = Bitmap.createBitmap(srcBitmap, 0, 0,
srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, false);
return bitmap;
}
/**
* 一般情况下,我们倾向于指定较长的一个边缩放情况(较短的进行等比例缩放)
* @param resId
* @param lastLongerLength
* @return
*/
public Bitmap scaleBitmap(Bitmap srcBitmap, int lastLongerLength) {
int srcWidth = srcBitmap.getWidth();
int srcHeight = srcBitmap.getHeight();
float scaleWidth = (float) lastLongerLength / srcWidth;
float scaleHeight = (float) lastLongerLength / srcHeight;
Matrix matrix = new Matrix();
float scaleRatio = Math.min(scaleWidth, scaleHeight);
matrix.postScale(scaleRatio, scaleRatio);
Bitmap bitmap = Bitmap.createBitmap(srcBitmap, 0, 0,
srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, false);
return bitmap;
}
3.有图有真相:
![看一下效果](https://img-blog.csdn.net/20150215153857005)