在开发中图片压缩几乎是离不开的一个话题,下边是几种压缩的方法,有用到的可以自取。
//谷歌官方根据图片大小计算缩放因子
private void setPic() {
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath, bmOptions);
imageView.setImageBitmap(bitmap);
}
//来自鲁班开源库
private fun compress(bitmap: Bitmap, path: String){
var option = BitmapFactory.Options()
option.inSampleSize = computeSize(bitmap.height,bitmap.width)
var img = BitmapFactory.decodeFile(path, option)
var fos = FileOutputStream(File(path))
//把图片输出到本地文件
img.compress(Bitmap.CompressFormat.JPEG,50,fos)
}
private fun computeSize(srcWidth:Int,srcHeight:Int): Int {
var srcWidth = if (srcWidth % 2 === 1) srcWidth + 1 else srcWidth
var srcHeight = if (srcHeight % 2 === 1) srcHeight + 1 else srcHeight
val longSide: Int = Math.max(srcWidth, srcHeight)
val shortSide: Int = Math.min(srcWidth, srcHeight)
val scale = shortSide.toFloat() / longSide
return if (scale <= 1 && scale > 0.5625) {
if (longSide < 1664) {
1
} else if (longSide < 4990) {
2
} else if (longSide > 4990 && longSide < 10240) {
4
} else {
if (longSide / 1280 == 0) 1 else longSide / 1280
}
} else if (scale <= 0.5625 && scale > 0.5) {
if (longSide / 1280 == 0) 1 else longSide / 1280
} else {
Math.ceil(longSide / (1280.0 / scale)).toInt()
}
}