先生成一个长宽被缩放的bitmap
public static void createCompressBitmap(String fileSource, File toFile) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// 获取这个图片的宽和高
Bitmap bitmap = BitmapFactory.decodeFile(fileSource, options); // 此时返回bm为空
options.inJustDecodeBounds = false;
// 计算缩放比
int be = (int) (options.outWidth / (float) 480);
if (be <= 0)
be = 1;
options.inSampleSize = be;
bitmap = BitmapFactory.decodeFile(fileSource, options);
if (bitmap == null) {
return;
}
// 解决翻转
Matrix matrix = new Matrix();
matrix.postRotate(readPictureDegree(fileSource)); /* 翻转 */
int width = bitmap.getWidth();
int height = bitmap.getHeight();
bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
compressBmpToFile(bitmap, toFile);
}
再压缩到100k以下
/**
* 压缩到100k以下
*
* @param bmp
* @param file
*/
public static void compressBmpToFile(Bitmap bmp, File file) {
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int options = 100;// 100表示不压缩
bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
while (baos.toByteArray().length / 1024 > 100) {
baos.reset();
options -= 10;
bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
}
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(baos.toByteArray());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
关于Bitmap的compress方法,android api 的截图
TIM截图20170315115709.png关于BitmapFactory.Options的inSampleSize
图片.png
网友评论