Skip to content

Instantly share code, notes, and snippets.

@clxy
Created November 25, 2016 14:13
Show Gist options
  • Save clxy/b310cac1aecf7f279f807e3ecbea2bf7 to your computer and use it in GitHub Desktop.
Save clxy/b310cac1aecf7f279f807e3ecbea2bf7 to your computer and use it in GitHub Desktop.
public final class AndroidImageUtil {
private AndroidImageUtil() {
}
/**
* 按图片尺寸压缩时,无法准确知道压缩后的文件大小。
* http://stackoverflow.com/questions/477572/strange-out-of-memory-issue-while-loading-an-image-to-a-bitmap-object/823966#823966
* @param file
* @return
*/
public static void compressImageByImageSize(File file, int newImageSize) {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
try {
FileInputStream fis = new FileInputStream(file);
BitmapFactory.decodeStream(fis, null, o);
fis.close();
int scale = 1;
if (o.outHeight > newImageSize || o.outWidth > newImageSize) {
scale = (int) Math.pow(
2,
(int) Math.ceil(
Math.log(newImageSize / (double) Math.max(o.outHeight, o.outWidth))
/ Math.log(0.5)
)
);
}
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(file);
Bitmap b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file);
b.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* http://www.graphicsmill.com/blog/2014/11/06/Compression-ratio-for-different-JPEG-quality-values#.V_5HeY997_U
* todo 初始文件6.xM,decode后82M(大文件恐怕会内存溢出),100压缩12M,95压缩6M...
* 曲线怪异。不如按图片尺寸压缩来的方便
* @param file
* @param fileSize
* @deprecated
*/
public static void compressImageByFileSize(File file, int fileSize) {
long length = file.length();
if (length <= fileSize) return;
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
int quality = 100 - bitmap.getByteCount() * 6 / fileSize;//105;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
byte[] bytes = null;
while (length >= fileSize && quality > 5) {
output.flush(); //to avoid out of memory error
output.reset();
quality -= 5;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, output);
bytes = output.toByteArray();
length = bytes.length;
Log.d(Util.class.getName(), "length=" + length + ";quality=" + quality);
}
FileOutputStream fo = new FileOutputStream(file);
fo.write(bytes);
fo.flush();
fo.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment