Uploading Rotated Image to Firebase - android

I'm try to accomplish the following task:
Selecting an image from Gallery
Rotating the image (if necessary) to the right orientation using ExifInterface
Upload the image to Firebase
Question
If image requires rotation, i'll end up with a rotated Bitmap file. How do i convert this Bitmap file to an Uri so that i can upload to Firebase?
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_INTENT && resultCode == Activity.RESULT_OK) {
mImageUri = data.getData();
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(),mImageUri);
rotatedBitmap = rotateImageIfRequired(getContext(), bitmap, mImageUri);
mVideoImage.setImageBitmap(rotatedBitmap);
imageHeight = bitmap.getHeight();
imageWidth = bitmap.getWidth();
}catch (IOException e){
e.printStackTrace();
}
}
private static Bitmap rotateImageIfRequired(Context context, Bitmap img, Uri selectedImage) throws IOException {
InputStream input = context.getContentResolver().openInputStream(selectedImage);
ExifInterface ei;
if (Build.VERSION.SDK_INT > 23)
ei = new ExifInterface(input);
else
ei = new ExifInterface(selectedImage.getPath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotateImage(img, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotateImage(img, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotateImage(img, 270);
default:
return img;
}
}
private static Bitmap rotateImage(Bitmap img, int degree) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
img.recycle();
return rotatedImg;
}

To upload a bitmap into FireBase storage, you need to turn it into a byte array. You can do this by creating a ByteArrayOutputStream.
ByteArrayOutputStream boas = new ByteArrayOutputStream();
Then compress the bitmap into a format like JPEG or PNG. The compress method takes 3 parameters, the format, the quality, and the ByteArrayOutputStream.
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, boas);
Then create a reference to your FireBase Storage Reference, where you want to put the photo.
String imageFileName = "ExampleName";
StorageReference ref = FirebaseStorage.getInstance().getReference().child("images").child(imageFileName);
Here, I created a folder called 'images' and a file inside which is named using the previously created imageFileName String
Then I can upload it to FireBase using an UploadTask by saying
UploadTask task = ref.putBytes(data);
Using this task, you can create success and failure listeners.
task.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});

Related

Image is saved in the correct format on FirebaseStorage, but the image is rotated when shared

I have the problem that I take a picture with the camera, then upload it to Firebase Storage, pack the DownloadLink into my RealtimeDatabase and then display the whole thing in a RecyclerView. The user can share the respective image via a share button. BUT the image is then not in the correct format. See last picture. It is saved correctly in the Firebase, then I download it when I click on the share button and then put it in an ACTION_SEND intent. However, the picture is rotated. How so ?
holder.sharing.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StorageReference islandRef = FirebaseStorage.getInstance().getReference("images").child(neu);
final long ONE_MEGABYTE = 1024 * 1024 * 5;
islandRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
ByteArrayOutputStream baos = null;
try {
BitmapFactory.Options options = new
BitmapFactory.Options();
options.inMutable = true;
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
String path = MediaStore.Images.Media.insertImage(ctx.getContentResolver(), bitmap, "Title", null);
Uri send = Uri.parse(path);
InputStream in= ctx.getContentResolver().openInputStream(send);
ExifInterface ei = new ExifInterface(in);
orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
Bitmap bitmapS = MediaStore.Images.Media.getBitmap(ctx.getContentResolver(), send);
Bitmap convert = getOrientation(bitmapS);
...
});
private Bitmap getOrientation(Bitmap bitmap){
Bitmap rotatedBitmap = null;
switch(orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotatedBitmap = rotateImage(bitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotatedBitmap = rotateImage(bitmap, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotatedBitmap = rotateImage(bitmap, 270);
break;
case ExifInterface.ORIENTATION_NORMAL:
default:
rotatedBitmap = bitmap;
}
return rotatedBitmap;
}
public static Bitmap rotateImage(Bitmap source, float angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(),
matrix, true);
}
If I pack the downloaded image directly into an intent, the image is rotated
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, send);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType("image/*");
ctx.startActivity(Intent.createChooser(intent, "Share with"));
On FirebaseStorage right format
On Android Code (Bitmap convert = getOrientation(bitmapS)) - wrong format

uploading image from imageview to server

I am attempting to upload an image from an android application to the server. I am calling the upload function and trying to get the image from ImageVeiw but no success. The image is set on the ImageVeiw from the gallery or camera.
Unable to get the file to send to the server
This is my code that I am using to set image from camera and gallery.
if(requestCode == CAMERA_REQUEST & resultCode == RESULT_OK){
Log.d("camera/gallery", "camera");
Bitmap photo = (Bitmap) data.getExtras().get("data");
profilePicture.setImageBitmap(photo);
} else if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Log.d("camera/gallery", "gallery");
// get image from gallery
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap loadedBitmap = BitmapFactory.decodeFile(picturePath);
// check orientation of image and rotate if required
ExifInterface exifInterface = null;
try{
File pictureFile = new File(picturePath);
exifInterface = new ExifInterface(pictureFile.getAbsolutePath());
} catch (IOException e){
e.printStackTrace();
}
int orientation = exifInterface.ORIENTATION_NORMAL;
if(exifInterface != null){
orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
}
switch(orientation){
case ExifInterface.ORIENTATION_ROTATE_90:
loadedBitmap = rotateBitmap(loadedBitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
loadedBitmap = rotateBitmap(loadedBitmap, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
loadedBitmap = rotateBitmap(loadedBitmap, 270);
break;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
loadedBitmap = flipBitmap(loadedBitmap, true, false);
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
loadedBitmap = flipBitmap(loadedBitmap, false, true);
default:
loadedBitmap = loadedBitmap;
}
// set image to ImageView
profilePicture.setImageBitmap(loadedBitmap);
}
I am able to get the bitmap image and trying to save it to the file. I am later trying to retrieve the same file and upload it to the server using retrofit
I am getting this error from retrofit on failure
W/System.err: java.io.FileNotFoundException: file:/data/user/0/com.example.fileuploaddemo/files/cleaton_profile_20191023T111341.png (No such file or directory)
Code for storing and retrieving the file and send the image file
public void uploadProfileImage(){
Uri fileUri = getSelectedFile();
if(Uri.EMPTY.equals(fileUri)){
Toast.makeText(this, "Exception Occurred", Toast.LENGTH_SHORT).show();
} else {
File originalFile = FileUtils.getFile(fileUri.toString());
Log.d(TAG, "in upload"+originalFile.getAbsolutePath());
RequestBody filePart = RequestBody.create(MediaType.parse("image/*"), originalFile);
MultipartBody.Part file = MultipartBody.Part.createFormData("upload", originalFile.getName(), filePart);
RequestBody modePart = RequestBody.create(MultipartBody.FORM, "profilepicture");
APIInterface apiInterface = APIClient.getClient().create(APIInterface.class);
apiInterface.uploadPhoto(file, modePart).enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Toast.makeText(MainActivity.this, "File Uploaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, "Upload Fail", Toast.LENGTH_SHORT).show();
t.printStackTrace();
}
});
}
}
public Uri getSelectedFile(){
try{
String username = "cleaton";
// get bitmap from image set on imageview and convert to byte array
BitmapDrawable bitmapDrawable = (BitmapDrawable) profilePicture.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
byte[] bitmapdata = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
String timeStamp = dateFormat.format(new Date());
File file = new File(getFilesDir(), username+"_profile_"+timeStamp+".png");
// insert byte array into file output stream with name
FileOutputStream fileOutputStream = openFileOutput(username+"_profile_"+timeStamp+".png", MODE_PRIVATE);
fileOutputStream.write(bitmapdata);
fileOutputStream.flush();
fileOutputStream.close();
File profileImageFile = new File(file.getAbsolutePath());
Log.d(TAG, "file retrieve"+profileImageFile);
Uri fileUri = Uri.fromFile(profileImageFile);
Log.d(TAG, "file Uri"+fileUri);
return fileUri;
} catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
return null;
}
catch(IOException ioe){
ioe.printStackTrace();
return null;
}
}
To expound on Webfreak's answer:
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
Once the Bitmap is retrieved, you can create a byte stream from which you can read the bytes and send those to your network socket by using a method similar to those below. Without knowing your upload method I am not sure if this is sufficient.
private InputStream getBitmapInputStream(BitmapFactory.Options options,
Bitmap bitmap) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(getCompressionFormat(options), 100 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
return new ByteArrayInputStream(bitmapdata);
}
private Bitmap.CompressFormat getCompressionFormat(BitmapFactory.Options options) {
if (options == null || options.outMimeType == null) return Bitmap.CompressFormat.JPEG;
if (options.outMimeType.endsWith("/png")) {
return Bitmap.CompressFormat.PNG;
} else if (options.outMimeType.endsWith("/webp")) {
return Bitmap.CompressFormat.WEBP;
} else {
return Bitmap.CompressFormat.JPEG;
}
}
Fist you need to get the bitmap from Imageview:
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
Once you have bitmap, you can upload it to server.

Selecting photo from new Google Photos app has incorrect orientation

I'm trying to choose a photo using intents on Android. All works well and photos are being retrieved from any photos app (camera, gallery, screenshots etc.. even if selected from the new Photos app); except for the ones backed up online on Google Photos.
Photos taken in portrait will be retrieved in landscape when getting the Bitmap. I have code to get the orientation of the photo so I can translate accordingly, but the orientation is always 0 when choosing an online photo on the new Google Photos app. Any ideas on how I should get the orientation for these photos as 0 is being returned? Code below - thanks.
Starting intent
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, IMPORT_PHOTO_RESULT);
Intent result
Uri selectedImageUri = data.getData();
imageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
//fix rotation
int orientation = -1;
Cursor cursor = MediaStore.Images.Media.query(getContentResolver(), selectedImageUri, new String[] { MediaStore.Images.ImageColumns.ORIENTATION });
try {
if (cursor.moveToFirst()) {
orientation = cursor.getInt(0);
}
} finally {
cursor.close();
}
imageBitmap = Utils.rotateImageWithRotation(orientation, imageBitmap);
//get stream to display and send
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
// get byte array here
byte[] bytearray = stream.toByteArray();
sendImage(bytearray, null);
rotate image
public static Bitmap rotateImageWithRotation(int rotationInDegrees, Bitmap mBitmap) {
Matrix matrix = new Matrix();
if (rotationInDegrees != 0f) {
matrix.preRotate(rotationInDegrees);
}
Bitmap adjustedBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), matrix, true);
return adjustedBitmap;
}
I gave up and used this amazing library instead. Kudos for the work!
https://github.com/coomar2841/image-chooser-library
You can try this:
Bitmap bitmap = null;
try {
Bitmap tmpBmp;
Uri uri = params[0]; // remove uri with uri from intent
int angle = 0;
Matrix m = new Matrix();
BitmapFactory.Options tempOption = new BitmapFactory.Options();
tempOption.inSampleSize = 2;
AssetFileDescriptor fileDescriptor = getContentResolver().openAssetFileDescriptor(uri, "r");
tmpBmp = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, tempOption);
ExifInterface ei = new ExifInterface(uri.getPath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
angle = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
angle = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
angle = 270;
break;
}
m.postRotate(angle);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
if (Runtime.getRuntime().totalMemory() > 64 * 1024 * 1024) {
options.inPreferredConfig = Bitmap.Config.RGB_565;
}
bitmap = Bitmap.createBitmap(tmpBmp, 0, 0, tempOption.outWidth, tempOption.outHeight, m, true);
} catch (Exception e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return bitmap;

Taking picture with camera intent rotate picture in portrait mode android

Picture was taken successfully with camera but in portrait mode on samsung galaxy s3 the picture gets rotated. How can i solve this issue.
Camera intent is as follows:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(xdestination));
startActivityForResult(intent, CAMERA_PIC_REQUEST);
In activity for result
if (requestCode==CAMERA_PIC_REQUEST){
// Bitmap bm = (Bitmap) data.getExtras().get("data");
Uri photo_uri = Uri.fromFile(xdestination);
Editer.PHOTO_FROM=11;
Bitmap decodeSampledBitmapFromFile=null;
try {
decodeSampledBitmapFromFile = decodeUri(photo_uri);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
decodeSampledBitmapFromFile.compress(Bitmap.CompressFormat.JPEG,100, bytes);
File f = new File(Environment.getExternalStorageDirectory(), "user_image.jpg");
try {
if(f.exists())
f.delete();
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
e.printStackTrace( );
Log.d("ERROR", e.toString());
}
}
Pass your taken picture and SDCard path of that picture into the following method which will return the correct oriented picture...
private Bitmap imageOreintationValidator(Bitmap bitmap, String path) {
ExifInterface ei;
try {
ei = new ExifInterface(path);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
bitmap = rotateImage(bitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
bitmap = rotateImage(bitmap, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
bitmap = rotateImage(bitmap, 270);
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
private Bitmap rotateImage(Bitmap source, float angle) {
Bitmap bitmap = null;
Matrix matrix = new Matrix();
matrix.postRotate(angle);
try {
bitmap = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(),
matrix, true);
} catch (OutOfMemoryError err) {
err.printStackTrace();
}
return bitmap;
}
Use :
public int getCameraPhotoOrientation(Context context, Uri imageUri, String imagePath){
int rotate = 0;
try {
context.getContentResolver().notifyChange(imageUri, null);
File imageFile = new File(imagePath);
ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
Log.i("RotateImage", "Exif orientation: " + orientation);
Log.i("RotateImage", "Rotate value: " + rotate);
} catch (Exception e) {
e.printStackTrace();
}
return rotate;
}
Try it like below.
File photo = new File(Environment.getExternalStorageDirectory(), "user_image.jpg");
if (photo.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(photo
.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
imageView.setRotation(90);
}
Step 1: Give a full path of your photo like File photo = new File(Environment.getExternalStorageDirectory()
, "Face.jpg");
Step 2: Check whether photo is exist or not if yes then set it to image view and rotate it to 90 degree.
You have no choice but read the image, rotate it and write the result back to SD card. The straightforward approach, using BitmapFactory, will easily run into OutOfMemory exception.
Alternatively, you can use JPEG lossless rotation, using jpegtran.
On SourceForge, there is a Java open source class LLJTran. The Android port is on GitHub.
Today I faced this problem. I know I'm late, but just in case someone needs it. In my case, if I pass the Uri inside the camera intent, then the output file was rotated. That is,
fun takePhoto() {
val intent = Intent(android.media.action.IMAGE_CAPTURE)
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(xdestination)) // <-- this line is the culprit for me
startActivityForResult(intent, CAMERA_PIC_REQUEST)
}
Then inside onActivity result, you get the bitmap rotated. I don't know why that happened.
So I didnot provide the Uri to the intent. That is I wrote this:
fun takePhoto() {
val intent = Intent(android.media.action.IMAGE_CAPTURE)
startActivityForResult(intent, CAMERA_PIC_REQUEST)
}
Therefore, inside onActivityResult I got the returned image as bitmap. Then I manually saved that bitmap inside the desired file / Uri.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PHOTO_CAPTURE_WITH_CAMERA_REQ_CODE && resultCode == RESULT_OK) {
// 1. handle the image as normal bitmap
val photo: Bitmap? = data?.extras?.get("data") as Bitmap;
// handleImage(SharedData.pendingPhotoUri.pop())
if (photo != null) {
// inside handle camera
handleCameraImage(photo)
};
}
}
private fun handleCameraImage(inputBitmap: Bitmap) {
//2. according to previous implementation, this uri should be the final output image file.
// 3. save the original bitmap in a temp image file
val tempBitmapFile: String = requireActivity().cacheDir.absolutePath +"/temp_photo_"+System.currentTimeMillis();
val fOuttemp: FileOutputStream = FileOutputStream(tempBitmapFile);
inputBitmap.compress(Bitmap.CompressFormat.PNG, 85, fOuttemp);
fOuttemp.flush();
fOuttemp.close();
// 4. use ExifInterface to make sure the photo is in right orientation.
val exifInterface: ExifInterface = ExifInterface(tempBitmapFile);
val orientation: Int = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
Timber.tag(TAG).e("orientation == " + orientation);
var matrix = Matrix();
var isRotationNeeded: Boolean = true;
when(orientation){
ExifInterface.ORIENTATION_NORMAL -> {
Timber.tag(TAG).e("when ExifInterface.ORIENTATION_NORMAL");
// do nothing I guess
isRotationNeeded = false;
}
ExifInterface.ORIENTATION_ROTATE_90 -> {
Timber.tag(TAG).e("when ExifInterface.ORIENTATION_ROTATE_90");
matrix.setRotate(90f);
}
ExifInterface.ORIENTATION_ROTATE_180 -> {
Timber.tag(TAG).e("when ExifInterface.ORIENTATION_ROTATE_180");
matrix.setRotate(180f);
}
ExifInterface.ORIENTATION_ROTATE_270 -> {
Timber.tag(TAG).e("when ExifInterface.ORIENTATION_ROTATE_270");
matrix.setRotate(270f);
}
else -> {
Timber.tag(TAG).e("when else");
isRotationNeeded = false;
}
}
// if in wrong orientation,
// rotate image and save it in the file from step 2.
// else save the original image in the file from step 2.
lateinit var outputBitmap: Bitmap;
if(!isRotationNeeded) {
outputBitmap = inputBitmap;
}else{
outputBitmap = Bitmap.createBitmap(inputBitmap, 0, 0, inputBitmap.width,
inputBitmap.height, matrix, true);
}
val outputBitmapfile: File = File("your_awesome_file");
val fOut: FileOutputStream = FileOutputStream(outputBitmapfile);
outputBitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
var outputPhotoUri:Uri = getUriForFile(requireActivty(), outputBitmapfile);
// 5. finally use this photo / Uri to do whatever you want
}
fun getUriForFile(context: Context, file: File?): Uri? {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N || Config.ONLY_INTERNAL_STORAGE) {
try {
val destCopiedTempFile = File(context.getExternalFilesDir(null).toString() + File.separator + "temp")
FileBackend.copy(file, destCopiedTempFile)
FileProvider.getUriForFile(context,
BuildConfig.APPLICATION_ID + ".fileprovider", destCopiedTempFile)
} catch (e: IllegalArgumentException) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
throw SecurityException(e)
} else {
Uri.fromFile(file)
}
}
} else {
Uri.fromFile(file)
}
}
This worked for me.

loading picture from library gets rotated

I am writing an android app and I am offering the user the ability to load a picture from the library.
The picture is loaded but rotated 90 degrees. Sometimes it is rotated -90 degrees.
How can I load the picture "the same way" it shows when you view it by your libray?
So if it is rotated then sure load it rotated it. But if it is correct, then it should be loaded the same way
Thank you very much
Sorry guys I should've added my code, Here it is:
try {
Intent choosePictureIntent = new Intent(Intent.ACTION_PICK, Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(choosePictureIntent, REQUEST_CHOOSE_IMAGE);
} catch (Exception e) {
e.printStackTrace();
}
break;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case REQUEST_CHOOSE_IMAGE:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream;
try {
imageStream = getContentResolver().openInputStream(selectedImage);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream, null, options );
ivPictureChosen.setImageBitmap(yourSelectedImage); //ivPictureChosen is image view to display the picture
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, "Couldn't pick image", Toast.LENGTH_SHORT).show();
}
}
}
}
I'm attempting the code below. It examines the orientation of the image and then rotates it accordingly. The issue I have is running out of memory and have yet to find a solution to exceeding the VM buget. This should work on smaller images and when your app is not already using a lot of memory.
ExifInterface ei = new ExifInterface(filePath);
int orientation = ei.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotateBitmap(bitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotateBitmap(bitmap, 180);
break;
}
public static void rotateBitmap(final Bitmap source, int mRotation){
int targetWidth=source.getWidth();
int targetHeight=source.getHeight();
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight, source.getConfig());
Canvas canvas = new Canvas(targetBitmap);
Matrix matrix = new Matrix();
matrix.setRotate(mRotation,source.getWidth()/2,source.getHeight()/2);
canvas.drawBitmap(source, matrix, new Paint());
}

Categories

Resources