9

Androidで、画像ファイルをJPEGとして30%の品質で保存するにはどうすればよいですか?

標準のJavaではImageIO、画像をとして読み取り、インスタンスBufferedImageを使用してJPEGファイルとして保存します。http: //www.universalwebservices.net/web-programming-resources/java/adjust-jpeg-image-compression -quality-when-saving-images-in-java。ただし、Androidにはパッケージがないようです。IIOImagejavax.imageio

4

4 に答える 4

19

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);

于 2011-01-02T18:10:06.757 に答える
4
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();
}
于 2011-01-02T20:31:56.050 に答える
2

@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();
于 2016-07-18T20:57:55.617 に答える
1

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")
    }
于 2019-02-08T09:48:11.773 に答える