【问题标题】:How to save a JPEG image on Android with a custom quality level如何在 Android 上以自定义质量级别保存 JPEG 图像
【发布时间】:2011-06-02 13:16:48
【问题描述】:
【问题讨论】:
标签:
java
android
jpeg
lossy-compression
【解决方案1】:
您可以通过调用 compress 并设置第二个参数来以 JPEG 格式存储位图:
Bitmap bm2 = createBitmap();
OutputStream stream = new FileOutputStream("/sdcard/test.jpg");
/* Write bitmap to file using JPEG and 80% quality hint for JPEG. */
bm2.compress(CompressFormat.JPEG, 80, stream);
【解决方案2】:
InputStream in = new FileInputStream(file);
try {
Bitmap bitmap = BitmapFactory.decodeStream(in);
File tmpFile = //...;
try {
OutputStream out = new FileOutputStream(tmpFile);
try {
if (bitmap.compress(CompressFormat.JPEG, 30, out)) {
{ File tmp = file; file = tmpFile; tmpFile = tmp; }
tmpFile.delete();
} else {
throw new Exception("Failed to save the image as a JPEG");
}
} finally {
out.close();
}
} catch (Throwable t) {
tmpFile.delete();
throw t;
}
} finally {
in.close();
}
【解决方案3】:
@Phyrum Tea 好只是别忘了关闭所有东西
InputStream in = new FileInputStream(context.getFilesDir() + "image.jpg");
Bitmap bm2 = BitmapFactory.decodeStream(in);
OutputStream stream = new FileOutputStream(String.valueOf(
context.getFilesDir() + pathImage + "/" + idPicture + ".jpg"));
bm2.compress(Bitmap.CompressFormat.JPEG, 50, stream);
stream.close();
in.close();
【解决方案4】:
使用Kotlin将path中的文件保存到tmpPath:
Files.newInputStream(path).use { inputStream ->
Files.newOutputStream(tmpPath).use { tmpOutputStream ->
BitmapFactory
.decodeStream(inputStream)
.compress(Bitmap.CompressFormat.JPEG, 30, tmpOutputStream)
}
}
编辑:确保检查解码失败(并返回 null)的可能性,以及压缩实际工作的可能性(布尔返回类型)。
val success: Boolean = Files.newInputStream(path).use { inputStream ->
Files.newOutputStream(tmpPath).use { tmpOutputStream ->
BitmapFactory
.decodeStream(inputStream)
?.compress(Bitmap.CompressFormat.JPEG, config.qualityLevel, tmpOutputStream)
?: throw Exception("Failed to decode image")
}
}
if (!success) {
throw Exception("Failed to compress and save image")
}