如何在安卓设备上以自定义质量级别保存JPEG图像

9
4个回答

19

通过调用compress方法并设置第二个参数,您可以将位图以JPEG格式存储:


    Bitmap bm2 = createBitmap();
    OutputStream stream = new FileOutputStream("/sdcard/test.jpg");
    /* 使用JPEG和80%的质量提示将位图写入文件。 */
    bm2.compress(CompressFormat.JPEG, 80, stream);


那个 .../test.png 是打错字了吗? - Sz.

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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接