I am creating an app that lets user select an image from gallery and store it in my DB.
I am successful in doing that.
Now I want that selected image to be deleted from phone storage also.
how do I do it then?
I might even want to restore it later in users gallery.
This is what I do to get image from gallery.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data)
{
switch (requestCode)
{
case 42:
if (resultCode == RESULT_OK)
{
Uri uri = data.getData();
InputStream inputStream = null;
try
{
inputStream = getBaseContext().getContentResolver().openInputStream(uri);
Bitmap bm = BitmapFactory.decodeStream(inputStream);
int maxHeight = 1920;
int maxWidth = 1920;
float scale = Math.min(((float) maxHeight / bm.getWidth()), ((float) maxWidth / bm.getHeight()));
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
saveImageToInternalStorage(bitmap, getFileName(uri));
bm.recycle();
bitmap.recycle();
finishActivity(42);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
}
This is the Uri path I'm getting
content://com.android.providers.media.documents/document/image%3A5857
my onActivityResult looks like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data)
{
switch (requestCode)
{
case 42:
if (resultCode == RESULT_OK)
{
Uri uri = data.getData();
InputStream inputStream = null;
try
{
inputStream = getBaseContext().getContentResolver().openInputStream(uri);
Bitmap bm = BitmapFactory.decodeStream(inputStream);
int maxHeight = 1920;
int maxWidth = 1920;
float scale = Math.min(((float) maxHeight / bm.getWidth()), ((float) maxWidth / bm.getHeight()));
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
saveImageToInternalStorage(bitmap, getFileName(uri));
bm.recycle();
bitmap.recycle();
finishActivity(42);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
}
Are you asking about this same question Delete image file from device programmatically Maybe you can get a solution from there.
try this
public static boolean delete(final Context context, final File file) {
final String where = MediaStore.MediaColumns.DATA + "=?";
final String[] selectionArgs = new String[] {
file.getAbsolutePath()
};
final ContentResolver contentResolver = context.getContentResolver();
final Uri filesUri = MediaStore.Files.getContentUri("external");
contentResolver.delete(filesUri, where, selectionArgs);
if (file.exists()) {
contentResolver.delete(filesUri, where, selectionArgs);
}
return !file.exists();
}
Related
I'm working in an app that take an image from the gallery and save it into parse.
The problem is that when I pick an image taken by the camera the size of the image is too big and takes some seconds to load the image in an image view. Also when I save the image and download again in the app it takes a lot of time because it has to download a big image.
I don't know how I reduce the size of the image picked. I tried several things but anything works.
This is my code at this moment
public class Datos extends Activity implements OnItemSelectedListener {
private final int SELECT_PHOTO = 1;
private ImageButton imageView;
ParseFile file;
byte [] data;
/*
public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(
bm, 0, 0, width, height, matrix, false);
bm.recycle();
return resizedBitmap;
}
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_datos);
btnClick();
imageView = (ImageButton) findViewById(R.id.imageButton);
ImageButton pickImage = (ImageButton) findViewById(R.id.imageButton);
pickImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
//photoPickerIntent.putExtra("outputX", 150);
//photoPickerIntent.putExtra("outputY", 100);
//photoPickerIntent.putExtra("aspectX", 1);
//photoPickerIntent.putExtra("aspectY", 1);
//photoPickerIntent.putExtra("scale", true);
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
try {
Uri imageUri = imageReturnedIntent.getData();
InputStream imageStream = getContentResolver().openInputStream(imageUri);
Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imageView.setImageBitmap(selectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
selectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
data = stream.toByteArray();
BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), selectedImage);
imageView.setBackgroundDrawable(bitmapDrawable);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bmp = drawable.getBitmap();
Bitmap b = Bitmap.createScaledBitmap(bmp, 120, 120, false);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
Spinner spinner = (Spinner) parent;
if (spinner.getId() == R.id.telefono) {
consola = parent.getItemAtPosition(position).toString();
} else if (spinner.getId() == R.id.provincia) {
provincia = parent.getItemAtPosition(position).toString();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public void btnClick() {
Button buttonEnviar = (Button) findViewById(R.id.enviar);
buttonEnviar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//Storing image in parse passed in onclick method of a button with the below code:
Intent intentDatos = new Intent(Datos.this, Inicio.class);
startActivity(intentDatos);
ParseObject testObject = new ParseObject("Musica");
if (data != null) {
file = new ParseFile("selected.png", data);
}
else {
data = "".getBytes();
file = new ParseFile("selected.png", data);
}
//file.saveInBackground();
testObject.put("imagen", file);
testObject.saveInBackground();
}
});
}
Does Anyone know how to do it?
Thanks for your help,
This answer will help you
if you want bitmap ratio same and reduce bitmap size. then pass your
maximum size bitmap. you can use this function
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float)width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
change your onActivityResult in SELECT_PHOTO case like this:
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
try {
Uri imageUri = imageReturnedIntent.getData();
InputStream imageStream = getContentResolver().openInputStream(imageUri);
Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
selectedImage = getResizedBitmap(selectedImage, 400);// 400 is for example, replace with desired size
imageView.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I am trying to let users select a profile picture from gallery. My issue is that some pictures come as rotated to the right.
I start the image picker like so:
Intent photoPickerIntent = new Intent();
photoPickerIntent.setType("image/*");
photoPickerIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(photoPickerIntent, "Select profile picture"), Global.CODE_SELECT_PICTURE);
I get the image from onActivityResult like so:
Uri selectedPicture = data.getData();
profilePic = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), selectedPicture);
How can i make have images not to be rotated?
UPDATE:
Following some of the helpful answers i have received, i managed to come up with the following working solution (It's just a working code, not well written). I would love to get your feedback on how i can improve it!
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == Global.CODE_SELECT_PICTURE) {
// Get selected gallery image
Uri selectedPicture = data.getData();
// Get and resize profile image
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = activity.getContentResolver().query(selectedPicture, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap loadedBitmap = BitmapFactory.decodeFile(picturePath);
ExifInterface exif = null;
try {
File pictureFile = new File(picturePath);
exif = new ExifInterface(pictureFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
int orientation = ExifInterface.ORIENTATION_NORMAL;
if (exif != null)
orientation = exif.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;
}
}
}
public static Bitmap rotateBitmap(Bitmap bitmap, int degrees) {
Matrix matrix = new Matrix();
matrix.postRotate(degrees);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
You could use ExifInterface to modify the orientation:
public static Bitmap modifyOrientation(Bitmap bitmap, String image_absolute_path) throws IOException {
ExifInterface ei = new ExifInterface(image_absolute_path);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotate(bitmap, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotate(bitmap, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotate(bitmap, 270);
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
return flip(bitmap, true, false);
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
return flip(bitmap, false, true);
default:
return bitmap;
}
}
public static Bitmap rotate(Bitmap bitmap, float degrees) {
Matrix matrix = new Matrix();
matrix.postRotate(degrees);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
public static Bitmap flip(Bitmap bitmap, boolean horizontal, boolean vertical) {
Matrix matrix = new Matrix();
matrix.preScale(horizontal ? -1 : 1, vertical ? -1 : 1);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
In order to get absolute path of your images from their uri, check this answer
2 One line solutions using Picasso and glide library
After spending a lot of time with a lot of solutions for image rotation problem I finally found two simple solutions. We don't need to do any additional works.
Using Picasso library https://github.com/square/picasso
Picasso.with(context).load("http url or sdcard url").into(imageView);
Using glide library https://github.com/bumptech/glide
Glide.with(this).load("http url or sdcard url").into(imgageView);
Picasso and Glide are a very powerful library for handling images in your app includes. It will read image EXIF data and auto-rotates the images.
I use these static methods. The first determines the orientation and the second rotates the image shrinking it as needed.
public static int getOrientation(Context context, Uri photoUri) {
Cursor cursor = context.getContentResolver().query(photoUri,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);
if (cursor == null || cursor.getCount() != 1) {
return 90; //Assuming it was taken portrait
}
cursor.moveToFirst();
return cursor.getInt(0);
}
/**
* Rotates and shrinks as needed
*/
public static Bitmap getCorrectlyOrientedImage(Context context, Uri photoUri, int maxWidth)
throws IOException {
InputStream is = context.getContentResolver().openInputStream(photoUri);
BitmapFactory.Options dbo = new BitmapFactory.Options();
dbo.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, dbo);
is.close();
int rotatedWidth, rotatedHeight;
int orientation = getOrientation(context, photoUri);
if (orientation == 90 || orientation == 270) {
Log.d("ImageUtil", "Will be rotated");
rotatedWidth = dbo.outHeight;
rotatedHeight = dbo.outWidth;
} else {
rotatedWidth = dbo.outWidth;
rotatedHeight = dbo.outHeight;
}
Bitmap srcBitmap;
is = context.getContentResolver().openInputStream(photoUri);
Log.d("ImageUtil", String.format("rotatedWidth=%s, rotatedHeight=%s, maxWidth=%s",
rotatedWidth, rotatedHeight, maxWidth));
if (rotatedWidth > maxWidth || rotatedHeight > maxWidth) {
float widthRatio = ((float) rotatedWidth) / ((float) maxWidth);
float heightRatio = ((float) rotatedHeight) / ((float) maxWidth);
float maxRatio = Math.max(widthRatio, heightRatio);
Log.d("ImageUtil", String.format("Shrinking. maxRatio=%s",
maxRatio));
// Create the bitmap from file
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = (int) maxRatio;
srcBitmap = BitmapFactory.decodeStream(is, null, options);
} else {
Log.d("ImageUtil", String.format("No need for Shrinking. maxRatio=%s",
1));
srcBitmap = BitmapFactory.decodeStream(is);
Log.d("ImageUtil", String.format("Decoded bitmap successful"));
}
is.close();
/*
* if the orientation is not 0 (or -1, which means we don't know), we
* have to do a rotation.
*/
if (orientation > 0) {
Matrix matrix = new Matrix();
matrix.postRotate(orientation);
srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(),
srcBitmap.getHeight(), matrix, true);
}
return srcBitmap;
}
I do it this way:
public void browseClick(View view) {
view.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.button_animation));
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
And the result where the orientation is checked will interest you most:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = 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);
Matrix matrix = new Matrix();
Bitmap scaledBitmap;
if (loadedBitmap.getWidth() >= loadedBitmap.getHeight()){
matrix.setRectToRect(new RectF(0, 0, loadedBitmap.getWidth(), loadedBitmap.getHeight()), new RectF(0, 0, 400, 300), Matrix.ScaleToFit.CENTER);
scaledBitmap = Bitmap.createBitmap(loadedBitmap, 0, 0, loadedBitmap.getWidth(), loadedBitmap.getHeight(), matrix, true);
} else{
matrix.setRectToRect(new RectF(0, 0, loadedBitmap.getWidth(), loadedBitmap.getHeight()), new RectF(0, 0, 300, 400), Matrix.ScaleToFit.CENTER);
scaledBitmap = Bitmap.createBitmap(loadedBitmap, 0, 0, loadedBitmap.getWidth(), loadedBitmap.getHeight(), matrix, true);
}
File file = new File(getExternalCacheDir(), "image.jpg");
try {
FileOutputStream out = new FileOutputStream(file);
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
Log.e("Image", "Convert");
}
imageView.setImageBitmap(scaledBitmap);
}
}
Here is the ExifInterface approach written in Kotlin:
fun modifyOrientation(bitmap: Bitmap, image_absolute_path: String): Bitmap {
val ei = ExifInterface(image_absolute_path)
val orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
return when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> rotateImage(bitmap, 90f)
ExifInterface.ORIENTATION_ROTATE_180 -> rotateImage(bitmap, 180f)
ExifInterface.ORIENTATION_ROTATE_270 -> rotateImage(bitmap, 270f)
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> flipImage(bitmap, true, false)
ExifInterface.ORIENTATION_FLIP_VERTICAL -> flipImage(bitmap, false, true)
else -> bitmap
}
}
private fun rotateImage(bitmap: Bitmap, degrees: Float): Bitmap {
val matrix = Matrix()
matrix.postRotate(degrees)
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
}
private fun flipImage(bitmap: Bitmap, horizontal: Boolean, vertical: Boolean): Bitmap {
val matrix = Matrix()
matrix.preScale((if (horizontal) -1 else 1).toFloat(), (if (vertical) -1 else 1).toFloat())
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
}
Using Picasso:
Picasso
.get()
.load("Your image path")
.into(imageView);
Picasso.with(this) is now replaced with Picasso.get()
Picasso library: https://github.com/square/picasso
Add : implementation 'com.squareup.picasso:picasso:2.71828' in build.gradle file.
Picasso will take care of image auto-rotation.
In my application I have added feature of image uploading,It works fine with all the Images except camera image,whenever I browse camera image from gallery and portrait image rotate in 90 degree..following is my snippet code..can anyone help me?I followed so many tutorials but all of them work well in kikat..but when same tutorial does not work with ics,jellybean etc..
public class MainActivity extends Activity {
private Button browse;
private String selectedImagePath="";
private ImageView img;
private TextView messageText;
private static int SELECT_PICTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView)findViewById(R.id.imagevw);
browse=(Button)findViewById(R.id.browseimg);
messageText = (TextView)findViewById(R.id.messageText);
browse.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
/*String filePath = getRealPathFromURI(getActivity(), selectedImageUri );
messageText.setText(filePath );
Picasso.with(getActivity())
.load(new File(filePath ))
.centerCrop()
.resize(60, 60).into( img);*/
selectedImagePath = getPath(selectedImageUri);
messageText.setText(selectedImagePath);
System.out.println(requestCode);
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
#SuppressWarnings("deprecation")
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
just include this code
public void rotateImage(String file) throws IOException{
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file, bounds);
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bm = BitmapFactory.decodeFile(file, opts);
int rotationAngle = getCameraPhotoOrientation(getActivity(), Uri.fromFile(file1), file1.toString());
Matrix matrix = new Matrix();
matrix.postRotate(rotationAngle, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
Bitmap rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bounds.outWidth, bounds.outHeight, matrix, true);
FileOutputStream fos=new FileOutputStream(file);
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
}
public static 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_UNDEFINED);
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
rotate = 0;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
return rotate;
}
There are several methods, but the simplest I found is by using Picasso library. As this is an uploading case, we will get the orientation correct and also can make adjustment in image bitmap size.
String filePath = getRealPathFromURI(getActivity(), selectedImageUri );
messageText.setText(filePath );
Picasso.with(getActivity())
.load(new File(filePath ))
.centerCrop()
.resize(60, 60).into( img);
I solved the image rotation problem with following code
public Bitmap rotateImageIfRequired(String imagePath) {
int degrees = 0;
try {
ExifInterface exif = new ExifInterface(imagePath);
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degrees = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degrees = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degrees = 270;
break;
}
} catch (IOException e) {
Log.e("ImageError", "Error in reading Exif data of " + imagePath, e);
}
BitmapFactory.Options decodeBounds = new BitmapFactory.Options();
decodeBounds.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, decodeBounds);
int numPixels = decodeBounds.outWidth * decodeBounds.outHeight;
int maxPixels = 2048 * 1536; // requires 12 MB heap
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = (numPixels > maxPixels) ? 2 : 1;
bitmap = BitmapFactory.decodeFile(imagePath, options);
if (bitmap == null) {
return null;
}
Matrix matrix = new Matrix();
matrix.setRotate(degrees);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
return bitmap;
}
When I pick an image from the gallery it is too large and I need to resize it. Can anyone give me suggestions on how I might be able to accomplish this?
See code below:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_GALLERY && resultCode == RESULT_OK) {
Uri uri = data.getData();
try {
bitmap = Media.getBitmap(this.getContentResolver(), uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
imageView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_GALLERY);
imageView.setImageBitmap(bitmap);
}
});
This post has some excellent samples for you: How to Resize a Bitmap in Android?
In your case, this method helps
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
Edit
Also from the same post, this fits your need in an easier way
Bitmap resizedBitmap = Bitmap.createScaledBitmap(originalBitmap, newWidth, newHeight, false);
Update
You can use the code in this way:
// Set the new width and height you want
int newWidth;
int newHeight;
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_GALLERY && resultCode == RESULT_OK) {
Uri uri = data.getData();
try {
bitmap = Media.getBitmap(this.getContentResolver(), uri);
bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The first file allow the user to pick a photo from the gallery and sends it to an activity which will process it. The problem is that the image is too large for the phone's screen, so you only see the top corner of the image(as if it has been magnified).
Button useGallery = (Button)findViewById(R.id.loadfromgallery);
useGallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}}) ;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case SELECT_PHOTO:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
Intent intent = new Intent(mContext, DisplayUndistortedBitmapFromGalleryActivity.class);
intent.setData(selectedImage);
startActivity(intent);
if(yourSelectedImage != null){
Log.e(TAG,"pic ok");
}else{
Log.e(TAG,"pic not ok");
}
}
}
. The 2nd file is the activity that recieves the image data from the intent and places it in a URI that a bitmap is the derived from.
public class DisplayUndistortedBitmapFromGalleryActivity extends Activity {
private static final String TAG = "*********DUBFGActivity";
private Context mContext = this;
Uri uri;
private Bitmap mbitmap = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
uri = getIntent().getData();
if(uri != null){
Log.e(TAG, "uri ok");
}else {
Log.e(TAG, "uri not ok");
}
try {
mbitmap = Media.getBitmap(getContentResolver(), uri);
//setMbitmap(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
.
I have a 3rd file which is the customview for the activity. The line below retrieves the bitmap from it's activity and displays it. Is there a way of downsizing the bitmap so it fits on the screen? thanks.
Bitmap bm = ((DisplayUndistortedBitmapFromGalleryActivity)getContext()).getMbitmap();
Here is how i usually resize a bitmap and is the easiest way.
public class bitmaptest extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout linLayout = new LinearLayout(this);
// load the origial BitMap (500 x 500 px)
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.android);
int width = bitmapOrg.width();
int height = bitmapOrg.height();
int newWidth = 200;
int newHeight = 200;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// rotate the Bitmap
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
width, height, matrix, true);
// make a Drawable from Bitmap to allow to set the BitMap
// to the ImageView, ImageButton or what ever
BitmapDrawable bmd = new BitmapDrawable
EDIT:
Here is another option.
int targetWidth = bitmapOrg.getWidth() - 15; //change this to control the size
int targetHeight = bitmapOrg.getHeight() - 15 ;
Matrix matrix = new Matrix();
matrix.postScale(1f, 1f);
Bitmap resizedBitmap = Bitmap.createBitmap(bmp, 0, 0, targetWidth, targetHeight, matrix, true);