如何使用自定义质量级别在Android上保存JPEG图像

时间:2011-01-02 17:52:55

标签: java android jpeg lossy-compression

在Android上,如何将图像文件保存为30%质量的JPEG?

在标准Java中,我会使用ImageIO将图像作为BufferedImage读取,然后使用IIOImage实例将其保存为JPEG文件:http://www.universalwebservices.net/web-programming-resources/java/adjust-jpeg-image-compression-quality-when-saving-images-in-java。但是,似乎Android缺少javax.imageio包。

4 个答案:

答案 0 :(得分:19)

您可以通过调用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);

答案 1 :(得分: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();
}

答案 2 :(得分:1)

@Phyrum茶是好的,不要忘了关闭一切

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

答案 3 :(得分:0)

使用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")
    }