Bitmap bmp = BitmapFactory.decodeFile(imgPath); //参数是图片绝对路径,从文件中获取Bitmap对象,当然这个方法可能会抛出异常,需要捕捉
//获取图片的宽和高
int width, height;
width = bmp.getWidth();
height = bmp.getHeight();
//newMatrix对象,postScale方法接受图片宽的比例和高的比例
Matrix matrix = new Matrix();
matrix.postScale(540 / (float)width, 540 / (float)width);
//根据原图创建新图像
Bitmap newBmp = Bitmap.createBitmap(bmp, 0, 0, width, height, matrix, true);
//当然还可以把压缩后的图片保存起来,比如保存到当前包的files目录下
FileOutputStream fos = context.openFileOutput("temp.jpg", Context.MODE_PRIVATE);
//这个方法用于向输出流输出数据,也就是可以保存文件,第一个参数是指定文件格式,可以试jpg和png格式,第二个参数是图片质量,最高为100
newBmp.compress(CompressFormat.JPEG, 100, fos);