7

I either take photo or select a photo from gallery and show it in an ImageView as it should be (in terms of rotation). But, whenever I upload it to server, it always uploads in landscape mode, even though it is in portrait mode in my gallery. How can I solve this?

private void takePhoto() {
    Intent takePhoto = new Intent();
    takePhoto.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
    File photoFile = null;
    try {
        photoFile = imagePath();
    } catch (IOException e) {
        Log.d(TAG, "Take Photo: " + e.getMessage());
    }
    takePhoto.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
    startActivityForResult(takePhoto, REQUEST_IMAGE);
}

private File imagePath() throws IOException {
    String timeStamp = new java.text.SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    String imageFileName = "IMAGE_" + timeStamp + "_";
    File storageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(imageFileName, ".jpg", storageDirectory);
    mImageLocation = image.getAbsolutePath();
    return image;
}

private void uploadMultipart() {
    String name = etName.getText().toString();
    String path = mImageLocation;

    try {
        String uploadId = UUID.randomUUID().toString();
        new MultipartUploadRequest(this, uploadId, API.IMAGE_UPLOAD_URL)
                .addFileToUpload(path, "image")
                .addParameter("name", name)
                .setNotificationConfig(new UploadNotificationConfig())
                .setMaxRetries(2)
                .startUpload();
    } catch (Exception e) {
        Log.d(TAG, "Upload: " + e.getMessage());
    }
}

private Bitmap setReducedImageSize() {
    int targetImageViewWidth = capturedPhoto.getWidth();
    int targetImageViewHeight = capturedPhoto.getHeight();

    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(mImageLocation, bmOptions);

    int cameraImageWidth = bmOptions.outWidth;
    int cameraImageHeight = bmOptions.outHeight;

    int scaleFactor = Math.min(cameraImageWidth / targetImageViewWidth, cameraImageHeight / targetImageViewHeight);
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inJustDecodeBounds = false;

    /*Bitmap reducedPhoto = BitmapFactory.decodeFile(mImageLocation, bmOptions);
    capturedPhoto.setImageBitmap(reducedPhoto);*/
    return BitmapFactory.decodeFile(mImageLocation, bmOptions);
}

private void rotateImage(Bitmap bitmap) {
    ExifInterface exifInterface = null;
    try {
        exifInterface = new ExifInterface(mImageLocation);
    } catch (IOException e) {
        Log.d(TAG, "Rotate Image: " + e.getMessage());
    }
    int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
    Matrix matrix = new Matrix();
    switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            matrix.setRotate(90);
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            matrix.setRotate(180);
            break;
        case ExifInterface.ORIENTATION_ROTATE_270:
            matrix.setRotate(270);
            break;
        default:
    }
    Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    capturedPhoto.setImageBitmap(rotatedBitmap);
}
Esteban
  • 667
  • 9
  • 22

1 Answers1

5

I spent some time few weeks ago facing the same issue. I made some digging and this is what I did to have my photo uploaded always in correct orientation : ). It works every time for every device. Hope it helps.

//this is the byte stream that I upload.
public static byte[] getStreamByteFromImage(final File imageFile) {

    Bitmap photoBitmap = BitmapFactory.decodeFile(imageFile.getPath());
    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    int imageRotation = getImageRotation(imageFile);

    if (imageRotation != 0)
        photoBitmap = getBitmapRotatedByDegree(photoBitmap, imageRotation);

    photoBitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);

    return stream.toByteArray();
}



private static int getImageRotation(final File imageFile) {

    ExifInterface exif = null;
    int exifRotation = 0;

    try {
        exif = new ExifInterface(imageFile.getPath());
        exifRotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (exif == null)
        return 0;
    else
        return exifToDegrees(exifRotation);
}

private static int exifToDegrees(int rotation) {
    if (rotation == ExifInterface.ORIENTATION_ROTATE_90)
        return 90;
    else if (rotation == ExifInterface.ORIENTATION_ROTATE_180)
        return 180;
    else if (rotation == ExifInterface.ORIENTATION_ROTATE_270)
        return 270;

    return 0;
}

private static Bitmap getBitmapRotatedByDegree(Bitmap bitmap, int rotationDegree) {
    Matrix matrix = new Matrix();
    matrix.preRotate(rotationDegree);

    return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
Rybzor
  • 183
  • 3
  • 12
  • Sorry for the late answer, but you do it with the File as an argument, while I do it with the path as an argument. How can I implement your code with the path? – Esteban Sep 20 '16 at 07:02
  • Just get your File object from a path and do the same? File photo = new File(PATH_TO_FILE); You can also notice that im not using any other file refference than **file.getPath()** so you can replace every occurance of **imageFile.getPath()** to **your_path**. Should be really simple : ) – Rybzor Sep 20 '16 at 14:17
  • Can you please let me know what type of connection do you use to upload the image to server? – Esteban Sep 22 '16 at 07:38
  • HTTP Post with photo byte stream in body. – Rybzor Sep 22 '16 at 09:02
  • @Rybzor Will it work , both with camera and gallery? I am also facing the same issue with samsung devices.In moto series it is working fine. – swetabh suman Jul 12 '17 at 17:08
  • Yes, it worked for me so I guess as long as you implement it the correct way this should be fine for you, too : ) – Rybzor Jul 13 '17 at 18:26
  • exif = new ExifInterface(imageFile.getPath()); returns 0 for me However, the image is still rotated.... – Gene Jul 24 '20 at 16:06