Android Bitmap图片的压缩,得到图片的一些方式:
//第一种方式:从资源文件中得到图片 Bitmap rawBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
//第二种方式:从SD卡中得到图片(方法1) String SDCarePath = Environment.getExternalStorageDirectory().toString(); String filePath = SDCarePath + "/" + "helloworld.png"; Bitmap rawBitmap1 = BitmapFactory.decodeFile(filePath, null);
//第二种方式:从SD卡中得到图片(方法2) InputStream inputStream = getBitmapInputStreamFromSDCard("helloworld.png"); Bitmap rawBitmap2 = BitmapFactory.decodeStream(inputStream);压缩图片的一些方式:
// 得到图片原始的高宽 int rawHeight = rawBitmap.getHeight(); int rawWidth = rawBitmap.getWidth(); // 设定图片新的高宽 int newHeight = 500; int newWidth = 500; // 计算缩放因子 float heightScale = ((float) newHeight) / rawHeight; float widthScale = ((float) newWidth) / rawWidth; // 新建立矩阵 Matrix matrix = new Matrix(); matrix.postScale(heightScale, widthScale); // 设置图片的旋转角度 //matrix.postRotate(-30); // 设置图片的倾斜 //matrix.postSkew(0.1f, 0.1f); //将图片大小压缩 //压缩后图片的宽和高以及kB大小均会变化
Bitmap newBitmap = Bitmap.createBitmap(rawBitmap, 0, 0, rawWidth, rawWidth, matrix, true);
//压缩图片并保存到文件中
rawBitmap.compress(Bitmap.CompressFormat.JPEG, quality, fileOutputStream);