カスタム品質レベルでAndroidにJPEG画像を保存する方法
-
14-10-2019 - |
質問
Androidでは、30%の品質でJPEGとして画像ファイルを保存するにはどうすればよいですか?
標準のJavaでは、使用します ImageIO
画像をaとして読むには BufferedImage
, 、次に、jpegファイルとして保存します IIOImage
実例: http://www.universalwebservices.net/web-promging-resources/java/adjust-jpeg-image-compression-quality-when-saving-images-in-java. 。ただし、Androidには不足しているようです javax.imageio
パッケージ。
解決
Compressを呼び出して2番目のパラメーターを設定することにより、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);
他のヒント
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();
}
@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();
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")
}
所属していません StackOverflow