GestureImagView in android - java

I'm using a GestureImageView Project that I've got from Github, I have several images in my drawable folder : page1.jpg, page2.jpg, page3.jpg,.........page30.jpg. I have a variable called pagenumber, when I click on a button this variable will increment, alson I want to load the image in the GestureImageView. Here is my code in the Main Class :
pagenumber++;
GestureImageView view1 = (GestureImageView) findViewById(R.id.image);
String uriPath = "android.resource://"+getPackageName()+"/drawable/page"+String.valueOf(pagenumber);
Uri uri = Uri.parse(uriPath);
view1 .setImageURI(uri);
In the GestureImageView.java the code is :
#Override
public void setImageURI(Uri mUri) {
if ("content".equals(mUri.getScheme())) {
try {
String[] orientationColumn = {MediaStore.Images.Media.ORIENTATION};
Cursor cur = getContext().getContentResolver().query(mUri, orientationColumn, null, null, null);
if (cur != null && cur.moveToFirst()) {
imageOrientation = cur.getInt(cur.getColumnIndex(orientationColumn[0]));
}
InputStream in = null;
try {
in = getContext().getContentResolver().openInputStream(mUri);
Bitmap bmp = BitmapFactory.decodeStream(in);
if(imageOrientation != 0) {
Matrix m = new Matrix();
m.postRotate(imageOrientation);
Bitmap rotated = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), m, true);
bmp.recycle();
setImageDrawable(new BitmapDrawable(getResources(), rotated));
}
else {
setImageDrawable(new BitmapDrawable(getResources(), bmp));
}
}
finally {
if(in != null) {
in.close();
}
if(cur != null) {
cur.close();
}
}
}
catch (Exception e) {
Log.w("GestureImageView", "Unable to open content: " + mUri, e);
}
}
else {
setImageDrawable(Drawable.createFromPath(mUri.toString()));
}
if (drawable == null) {
Log.e("GestureImageView", "resolveUri failed on bad bitmap uri: " + mUri);
// Don't try again.
mUri = null;
}
}
Well I'm having an empty image in the GestureImageView, it's not loading. The logcat says Unable to decode stream : java.io.FileNotFoundException: /android.resource:/com.example.tests/drawable/page3 : open failed : ENOENT (No such file or directory). I also tried to add the .png extension but I had the same result.
Please note that when I use an imageview instead of GestureImageView it works
Any help please ?

Related

When i select image from recent then image is broken in android | Multiple images from recent

This error occurs mostly times when select images from recent folder
class com.bumptech.glide.load.engine.GlideException: Received null model
Call multiple images select
Sample Preview
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
*gallery*.launch(i);
gallery basically startActivityForResult(i,123) and OnActivityResult method is deprecated, the gallery is alternative which is defined below
ActivityResultLauncher<Intent> gallery = choosePhotoFromGallery();
and choosePhotoFromGallery() is method which is define below
private ActivityResultLauncher<Intent> choosePhotoFromGallery() {
return registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
try {
if (result.getResultCode() == RESULT_OK) {
if (null != result.getData()) {
if (result.getData().getClipData() != null) {
ClipData mClipData = result.getData().getClipData();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
String imageFilePathColumn = getPathFromURI(this, uri);
productImagesList.add(imageFilePathColumn);
}
} else {
if (result.getData().getData() != null) {
Uri mImageUri = result.getData().getData();
String imageFilePathColumn = getPathFromURI(this, mImageUri);
productImagesList.add(imageFilePathColumn);
}
}
} else {
showToast(this, "You haven't picked Image");
productImagesList.clear();
}
} else {
productImagesList.clear();
}
} catch (Exception e) {
e.printStackTrace();
showToast(this, "Something went wrong");
productImagesList.clear();
}
});
}
and getPathFromURI() is method which define below
public String getPathFromURI(Context context, Uri contentUri) {
OutputStream out;
File file = getPath();
try {
if (file.createNewFile()) {
InputStream iStream = context != null ? context.getContentResolver().openInputStream(contentUri) : context.getContentResolver().openInputStream(contentUri);
byte[] inputData = getBytes(iStream);
out = new FileOutputStream(file);
out.write(inputData);
out.close();
return file.getAbsolutePath();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
and the getPath() is
private File getPath() {
File folder = new File(Environment.getExternalStorageDirectory(), "Download");
if (!folder.exists()) {
folder.mkdir();
}
return new File(folder.getPath(), System.currentTimeMillis() + ".jpg");
}
THANK YOU IN ADVANCE HAPPY CODING

How to convert xml layouts to image?

In my Android project I have more than 100 xml layouts.
Is there a function in Android Studio where I can screenshot my layout?
I want to convert all my layouts to jpeg or png for my company report.
In this function you just have to pass the view it will give you bitmap you can store it or show it on imageview
public void takeScreenshot(View screenshotView) {
try {
View view = null;
Bitmap b = null;
if (screenshotView instanceof TextureView) {
b = ((TextureView) screenshotView).getBitmap();
} else {
view = screenshotView;
}
if (view != null) {
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
b = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
}
if (imageViewParentLayout != null) {
if (imageView != null) {
imageView.setVisibility(View.VISIBLE);
imageView.setImageBitmap(b);
}
}
String path = saveToAlbum(b);
Notify.INSTANCE.Toast("Image Saved :" + path);
scanfiles(path);
} catch (Exception e) {
e.printStackTrace();
Notify.INSTANCE.Toast("Something Went Wrong");
}finally {
hideImageView();
}
}
private void scanfiles(String path) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
File outputFile = new File(path);
final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
final Uri contentUri = Uri.fromFile(outputFile);
scanIntent.setData(contentUri);
AppController.getAppContext().sendBroadcast(scanIntent);
} else {
final Intent intent = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()));
AppController.getAppContext().sendBroadcast(intent);
}
} catch (Exception e) {
e.printStackTrace();
File file=new File(path);
MediaScannerConnection.scanFile(AppController.getAppContext(), new String[]{
file.getAbsolutePath()},
null, (path1, uri) -> {
});
}
}

How to fix null error in getWidth() on bitmap [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
In my application i want to select image from gallery and compress it.
For compress i use this library : https://github.com/zetbaitsu/Compressor
I wrote below codes for it, but when i run the application and select image from gallery, it throws force close and show below errors in logCat :
My activity codes :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_PHOTO || requestCode == REQUEST_PICK_PHOTO) {
if (data != null) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mediaPath = cursor.getString(columnIndex);
cursor.close();
postPath = mediaPath;
uploadImageToServer(postPath);
}
}
} else if (resultCode != RESULT_CANCELED) {
}
}
}
private void uploadImageToServer(String imagePath) {
if (imagePath == null || imagePath.equals("")) {
return;
} else {
showpDialog();
Map<String, RequestBody> map = new HashMap<>();
File file = new File(imagePath);
try {
compressedImage = new Compressor(getActivity())
.setMaxWidth(2000)
.setMaxHeight(1400)
.setQuality(90)
.setCompressFormat(Bitmap.CompressFormat.JPEG)
.setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getAbsolutePath())
.compressToFile(file);
} catch (IOException e) {
e.printStackTrace();
}
}
LogCat error :
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
at id.zelory.compressor.ImageUtil.decodeSampledBitmapFromFile(ImageUtil.java:70)
at id.zelory.compressor.ImageUtil.compressImage(ImageUtil.java:33)
at id.zelory.compressor.Compressor.compressToFile(Compressor.java:60)
at id.zelory.compressor.Compressor.compressToFile(Compressor.java:56)
at com.app.android.Fragments.NewAddressFragment.uploadImageToServer(NewAddressFragment.java:486)
at com.app.android.Fragments.NewAddressFragment.onActivityResult(NewAddressFragment.java:353)
at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:156)
at android.app.Activity.dispatchActivityResult(Activity.java:7295)
Show error for this line : .compressToFile(file);
UPDATE : show this error just for some images no all images!
How can i fix it? please help me
Another assumption on GitHub is, that you probably try to store the changed file with the original name in the original path. This also may lead to problems. Please try this version of code. I added compressedFileName.
private void uploadImageToServer(String imagePath) {
if (imagePath == null || imagePath.equals("")) {
return;
} else {
showpDialog();
Map<String, RequestBody> map = new HashMap<>();
File file = new File(imagePath);
if(file != null && file.exists() && file.canRead()) {
try {
String compressedFileName = "_" + file.getName();
compressedImage = new Compressor(getActivity())
.setMaxWidth(2000)
.setMaxHeight(1400)
.setQuality(90)
.setCompressFormat(Bitmap.CompressFormat.JPEG)
.setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getAbsolutePath())
.compressToFile(file, compressedFileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Please handle through try and catch block and show dialog message to user for select another image, may be selected image is corrupted.
Just make sure that file is not null.
private void uploadImageToServer(String imagePath) {
if (imagePath == null || imagePath.equals("")) {
return;
} else {
showpDialog();
Map<String, RequestBody> map = new HashMap<>();
File file = new File(imagePath);
if(file != null && file.exists() && file.canRead()) {
try {
compressedImage = new Compressor(getActivity())
.setMaxWidth(2000)
.setMaxHeight(1400)
.setQuality(90)
.setCompressFormat(Bitmap.CompressFormat.JPEG)
.setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getAbsolutePath())
.compressToFile(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

how to upload few images use bitmapFactory?

How can I upload images one by one so that the memory is cleared each time after the picture upload has been successfully downloaded and the picture does not disappear from the screen?
Trying to load few images in RecyclerView. Important! Images are loaded from other applications (themes for my app).
Here is the code:
private static final int MAX_SAMPLE = 16;
private static Drawable getDrawableFromResource(Resources themeRes, int resourceID)
{
if (resourceID == 0 || themeRes == null)
return null;
Drawable drawable = null;
Bitmap bitmap = null;
BitmapFactory.Options uniformOptions = new BitmapFactory.Options();
int inputSampleSize = uniformSampleSize;
if (inputSampleSize > MAX_SAMPLE)
inputSampleSize = MAX_SAMPLE;
String resName = getResName(resourceID);
for (int sizeDivider = inputSampleSize; sizeDivider <= MAX_SAMPLE; sizeDivider *= 2)
{
uniformOptions.inSampleSize = sizeDivider;
try
{ bitmap = BitmapFactory.decodeResource(themeRes, resourceID, uniformOptions); }
catch (OutOfMemoryError | Exception e)
{
Log.e(DynamicSettings.TAG_ERROR, "Load drawable: " + (resName != null ? resName : "name not found") + ", sizeDiv: " + sizeDivider);
e.printStackTrace();
continue;
}
try
{
drawable = new BitmapDrawable(bitmap);
return drawable;
}
catch (OutOfMemoryError | Exception e)
{
Log.e(DynamicSettings.TAG_ERROR, "Bad drawable resource file (parsing): " + resName);
e.printStackTrace(); // Out of memory or Null pointer
if (bitmap != null)
bitmap.recycle();
}
}
new BitmapDrawable(getErrorBitmap());
return new BitmapDrawable(getErrorBitmap());
}
If there is not enough memory for all the pictures – they resize using inSampleSize uniformOptions
Here's the error:
If you call bitmap.recycle() or something like that - image dissapear from RecyclerView and throw exception.

Image Orientation - Android

I have been struggling with this bug on and off for the last month or so. Everytime that I think I have fixed it it seems to come back in some form.
It is the old Android "Image Rotated 90 degrees" bug. I have read countless Posts on here (StackOverFlow) aswell as tried numerous methods but just cannot seem to fix it.
I am still getting images that are rotated incorrectly.
In my application a user chooses his/her profile Picture, which is then set to an ImageView. The image is chosen from the Phones Gallery
Two days ago I implemented the Following Code, this worked for all the images I tested it with on my Phone. However when one of my Beta testers tried it, his images were once again rotated. He sent me the images for testing but they were displaying fine on my Phone. Hence why I am getting more and more frustrated.
This is the method I am using to get the Images orientation:
// Gets an Images Orientation
public static int getOrientationEXIF(Context context, Uri uri) {
int orientation = 0;
try {
ExifInterface exif = new ExifInterface(uri.getPath());
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
orientation = 90;
return orientation;
case ExifInterface.ORIENTATION_ROTATE_180:
orientation = 180;
return orientation;
}
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
I then get a rotated Bitmap using this Method:
// Rotate a Bitmap
public static Bitmap rotate(float rotationValue, String filePath) {
Bitmap original= BitmapFactory.decodeFile(filePath);
int width = original.getWidth();
int height = original.getHeight();
Matrix matrix = new Matrix();
matrix.postRotate(rotationValue);
Bitmap rotated = Bitmap.createBitmap(original, 0, 0, width, height, matrix, true);
return rotated;
}
I am just not sure what to do anymore.
I would really like it if someone could help me figure this out
Thank you in advance
UPDATE
I just saw the following line of Code in my Log after implementing the suggested Methods:
JHEAD can't open 'file:/external/images/media/3885'
I am not sure what this means
UPDATE #2
I think I may have fixed the problem, I got the proper image path for the file.
You need to account for all orientations not just 90 or 180. I am using this
File curFile = new File("path-to-file"); // ... This is an image file from my device.
Bitmap rotatedBitmap;
try {
ExifInterface exif = new ExifInterface(curFile.getPath());
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(rotation);
Matrix matrix = new Matrix();
if (rotation != 0f) {matrix.preRotate(rotationInDegrees);}
rotatedBitmap = Bitmap.createBitmap(bitmap,0,0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}catch(IOException ex){
Log.e(TAG, "Failed to get Exif data", ex);
}
and:
/**
* Gets the Amount of Degress of rotation using the exif integer to determine how much
* we should rotate the image.
* #param exifOrientation - the Exif data for Image Orientation
* #return - how much to rotate in degress
*/
private static int exifToDegrees(int exifOrientation) {
if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { return 90; }
else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) { return 180; }
else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) { return 270; }
return 0;
}
This problem really sucks ! I notice this is an issue when choosing photos rather than taking them. I found the answer buried in the code for this cropping lib which seemed to always display things correctly https://github.com/jdamcd/android-crop while cropping (despite it sometimes returning things with wrong orientation afterwards). Anyways, first start off by choosing the photo the way I choose in this answer: Pick image from fragment always return resultcode 0 in some devices
Next do this where you need to:
private void setRotationVariables(Uri uri)
{
m_rotationInDegrees = ImageOrientationUtil.getExifRotation(ImageOrientationUtil
.getFromMediaUri(
this,
getContentResolver(),
uri));
}
Here is the class:
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import java.io.Closeable;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ImageOrientationUtil
{
private static final String SCHEME_FILE = "file";
private static final String SCHEME_CONTENT = "content";
public static void closeSilently(#Nullable Closeable c) {
if (c == null) return;
try {
c.close();
} catch (Throwable t) {
// Do nothing
}
}
public static int getExifRotation(File imageFile) {
if (imageFile == null) return 0;
try {
ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
// We only recognize a subset of orientation tag values
switch (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)) {
case ExifInterface.ORIENTATION_ROTATE_90:
return 90;
case ExifInterface.ORIENTATION_ROTATE_180:
return 180;
case ExifInterface.ORIENTATION_ROTATE_270:
return 270;
default:
return ExifInterface.ORIENTATION_UNDEFINED;
}
} catch (IOException e) {
// Log.e("Error getting Exif data", e);
return 0;
}
}
#Nullable
public static File getFromMediaUri(Context context, ContentResolver resolver, Uri uri) {
if (uri == null) return null;
if (SCHEME_FILE.equals(uri.getScheme())) {
return new File(uri.getPath());
} else if (SCHEME_CONTENT.equals(uri.getScheme())) {
final String[] filePathColumn = { MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME };
Cursor cursor = null;
try {
cursor = resolver.query(uri, filePathColumn, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
final int columnIndex = (uri.toString().startsWith("content://com.google.android.gallery3d")) ?
cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME) :
cursor.getColumnIndex(MediaStore.MediaColumns.DATA);
// Picasa images on API 13+
if (columnIndex != -1) {
String filePath = cursor.getString(columnIndex);
if (!TextUtils.isEmpty(filePath)) {
return new File(filePath);
}
}
}
} catch (IllegalArgumentException e) {
// Google Drive images
return getFromMediaUriPfd(context, resolver, uri);
} catch (SecurityException ignored) {
// Nothing we can do
} finally {
if (cursor != null) cursor.close();
}
}
return null;
}
private static String getTempFilename(Context context) throws IOException {
File outputDir = context.getCacheDir();
File outputFile = File.createTempFile("image", "tmp", outputDir);
return outputFile.getAbsolutePath();
}
#Nullable
private static File getFromMediaUriPfd(Context context, ContentResolver resolver, Uri uri) {
if (uri == null) return null;
FileInputStream input = null;
FileOutputStream output = null;
try {
ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r");
FileDescriptor fd = pfd.getFileDescriptor();
input = new FileInputStream(fd);
String tempFilename = getTempFilename(context);
output = new FileOutputStream(tempFilename);
int read;
byte[] bytes = new byte[4096];
while ((read = input.read(bytes)) != -1) {
output.write(bytes, 0, read);
}
return new File(tempFilename);
} catch (IOException ignored) {
// Nothing we can do
} finally {
closeSilently(input);
closeSilently(output);
}
return null;
}
}
mochilogic answer is very good but his comment is also correct:
sorry, " do this where you need to " is so vague.."
I cannot add all of this in comment to mochilogic answer so I will write this here: If you dont like touse it in setRotationVariables(data.getData) - this is another way to use the class ImageOrientationUtil from his answer and this method:
private void setRotationVariables(Uri uri)
{
m_rotationInDegrees = ImageOrientationUtil.getExifRotation
(ImageOrientationUtil.getFromMediaUri(
this,
getContentResolver(),
uri));
}
You can send Uri from the galery to this method make it return the correct rotation in degrees by memebr as he does or by value as I did:
private static int setRotationVariables(Uri uri) {
int rotationInDegrees = ImageOrientationUtil.getExifRotation(ImageOrientationUtil
.getFileFromMediaUri(
appCtx,
appCtx.getContentResolver(),
uri));
Log.d(TAG, "setRotationVariables:" + "according to original Image Uri Exif details we need to rotate in "+rotationInDegrees + " Degrees");
return rotationInDegrees;
}
and then on the calling function after you scale your Uri to bitmap you can create bitmap using this rotationInDegrees with a matrix.
you can see it in my code here in this method I take Uri and scale it and rotate it and then returns it as bitmap.
but first - basicaly this is what you need:
int rotationDegree = setRotationVariables(uri);
if (rotationDegree > 0) {
Matrix matrix = new Matrix();
matrix.setRotate(rotationDegree);
Log.w(TAG, "recreating bitmap with rotation of " + rotationDegree + " degrees" );
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
This is the full method code if anyones need it..
public static Bitmap getScaledBitmapFromUri(Uri uri) throws FileNotFoundException, IOException {
final int TRY_SCALE_TO_THIS_SIZE = 1024;
Log.d(TAG, "getScaledBitmapFromUri:: calling setRotationVariables() to figure rotationDegree");
int rotationDegree = setRotationVariables(uri);
Context ctx = MessagingApp.getContext();
InputStream input = ctx.getContentResolver().openInputStream(uri);
BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
onlyBoundsOptions.inJustDecodeBounds = true;
onlyBoundsOptions.inDither = true;//optional
onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
input.close();
if ( (onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1) )
return null;
int BiggestOriginalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth;
//we will add 1 to Math.round (BiggestOriginalSize / (double)TRY_SCALE_TO_THIS_SIZE) in order to harden the scaling(we need smaller images for this project!)
double ratio = (BiggestOriginalSize > TRY_SCALE_TO_THIS_SIZE) ? (1 + Math.round(BiggestOriginalSize / (double) TRY_SCALE_TO_THIS_SIZE)) : 1.0;
Log.w(TAG, "getScaledBitmapFromUri:: originalSize: " + BiggestOriginalSize + "PX, TRY_SCALE_TO_THIS_SIZE (if original is bigger):" + TRY_SCALE_TO_THIS_SIZE +"PX");
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio); //this one will give abstract results (sometimes bigger then TRY_SCALE_TO_THIS_SIZE)
Log.w(TAG, format("bitmapOptions.inSampleSize: " + bitmapOptions.inSampleSize));
bitmapOptions.inJustDecodeBounds = false; //check this out!!! maybe delete?
bitmapOptions.inDither = true;//optional
bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
//bitmapOptions.rogetrotationInDegrees
input = ctx.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
//bitmap = findExactInSampleSize(onlyBoundsOptions, TRY_SCALE_TO_THIS_SIZE, bitmap); // this one will never give bigger length then TRY_SCALE_TO_THIS_SIZE
if (rotationDegree > 0) {
Matrix matrix = new Matrix();
matrix.setRotate(rotationDegree);
Log.w(TAG, "recreating bitmap with rotation of " + rotationDegree + " degrees" );
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
Log.w(TAG, "after decodeStream : bitmap.getWidth(): " + bitmap.getWidth() + "PX, bitmap.getHeight(): " + bitmap.getHeight() +"PX.");
input.close();
return bitmap;
}

Categories

Resources