Android – how to get or set (print) DPI ( dots per inch ) of JPEG file while loading or saving it programmatically?

Just for convenience here is ready to copy and paste method:

public static void saveBitmapToJpg(Bitmap bitmap, File file, int dpi) throws IOException {
    ByteArrayOutputStream imageByteArray = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, imageByteArray);
    byte[] imageData = imageByteArray.toByteArray();

    setDpi(imageData, dpi);

    FileOutputStream fileOutputStream = new FileOutputStream(file);
    fileOutputStream.write(imageData);
    fileOutputStream.close();
}

private static void setDpi(byte[] imageData, int dpi) {
    imageData[13] = 1;
    imageData[14] = (byte) (dpi >> 8);
    imageData[15] = (byte) (dpi & 0xff);
    imageData[16] = (byte) (dpi >> 8);
    imageData[17] = (byte) (dpi & 0xff);
}

saved file will have properly set Image DPI value:

enter image description here

Leave a Comment