Enrique Márquez
Enrique Márquez

Reputation: 103

Android - When sending images to the server in vertical, they are rotated although the preview in the mobile looks good

The preview on the phone looks good before sending the file, but once it is received on the server and reloaded on the mobile is rotated vertical images.

public static File saveBitmapTemporarily(Bitmap finalBitmap, int extension, ExifInterface oldExif) {
    String root = Environment.getExternalStorageDirectory().toString();

    FileUtils.createFolder(new File(Environment.getExternalStorageDirectory() + BuildConfig.STORAGE_DIR));

    File myDir = new File(root + BuildConfig.STORAGE_DIR + "/");
    myDir.mkdirs();
    String fname;
    if (extension == IMAGE_FORMAT_JPG_JPEG) {
        fname = "file-reduced.jpg";
    } else {
        fname = "file-reduced.png";
    }
    File file = new File(myDir, fname);
    if (file.exists()) file.delete();
    try {
        FileOutputStream out = new FileOutputStream(file);
        if (extension == IMAGE_FORMAT_JPG_JPEG) {
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        } else {
            finalBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        }
        out.flush();
        out.close();

    } catch (Exception e) {
        if (BuildConfig.DEBUG)
            e.printStackTrace();
    }

    return file;
}

Upvotes: 3

Views: 59

Answers (1)

Mr.Moustard
Mr.Moustard

Reputation: 1307

Welcome to Stack Overflow @kiketurry... Here you have what I did to solve this problem. You should store the width and height dimension in the exif data of the photo so that the server knows how to orient it, but it can only be in jpg

if (extension == IMAGE_FORMAT_JPG_JPEG) {
    ExifInterface oldExif = null;
    try {
        oldExif = new ExifInterface(file.getAbsolutePath());
        ExifInterface newExif;
        newExif = new ExifInterface(file.getAbsolutePath());
        newExif.setAttribute("ImageLength", String.valueOf(finalBitmap.getHeight()));
        newExif.setAttribute("ImageWidth", String.valueOf(finalBitmap.getWidth()));
        if (oldExif != null) {
            String exifOrientation = oldExif.getAttribute(ExifInterface.TAG_ORIENTATION);
            if (exifOrientation != null) {
                newExif.setAttribute(ExifInterface.TAG_ORIENTATION, exifOrientation);
            }
        }
        newExif.saveAttributes();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

I hope it helps.

Upvotes: 4

Related Questions