Java >> Java Tutorial >  >> Java

So speichern Sie ein JPEG-Bild auf Android mit einer benutzerdefinierten Qualitätsstufe

Sie können Ihre Bitmap im JPEG-Format speichern, indem Sie compress aufrufen und den zweiten Parameter setzen:


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

Java-Tag