Android resize gallery image - android

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();
}
}
}

Related

How can I set the size of Image when imported in Android?

I am using the following code to let a user import an image from their gallery into the app.
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
But, I want the size of the image to be a certain size no matter what the image size they have imported is. Whenever I import an image it always fill the whole screen. Let's say I want the image size to be 50 width by 50 height.
There are two ways to set the imageview size
from the xml
<ImageView
android:id="#+id/image_view"
android:layout_width="200dp"
android:layout_height="100dp"
android:scaleType="fitCenter"
android:src="#drawable/iclauncher"
android:scaleType="fitXY"/>
from programmatically
image_view.getLayoutParams().height = 20;
image_view.getLayoutParams().width = 20;
this is the way to resize bitmap image
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;
}
As suggested by saeed:
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(decodeUri(this, Uri.parse(imgDecodableString), 50));
Where decodeUri is from here.

resize image picked from gallery

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();
}
}

How resize image from gallery?

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);

Image blur in android

I have taken thumbnail image from gallery which is smaller in size and resized into 300*300 size.
By doing that the image looking so blurred.
getting image from gallery
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
try {
flag = 1;
Uri selectedImage = imageReturnedIntent.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 filePath = cursor.getString(columnIndex); // file
// path
// of
// selected
// image
cursor.close();
// Convert file path into bitmap image using below line.
yourSelectedImage = download.getResizedBitmap(
image.decodeImage(filePath),270,228);
// put bitmapimage in your imageview
profile_image.setImageBitmap(
yourSelectedImage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Image resizing
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
{
try
{
if(bm!=null)
{
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
resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
}
}
catch(Exception e)
{
e.printStackTrace();
}
return resizedBitmap;
}
Images get blurred when you enlarge them (unless you are using an vector image and you are using a bitmap). Your getResizedBitmap method doesn't do anything much other than stretching the image to fit the new size. The only way you are going to solve your problem is by selecting larger images (but then eventually you will run into the aspect ratio problem, so you should really rethink your scaling algorithm).
Of course enlarging a bitmap image will be pixelated..

How to resolve null pointer exception during camera capture in Android

How to resolve null pointer exception that occurred when I try to use Intent.putExtra() in calling camera activity.
public class ImageCaptureActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Uri mImageCaptureUri = Uri.fromFile(new File("/sdcard/gift2.JPG"));
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
startActivityForResult(intent, 0);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == Activity.RESULT_OK) { <br> Toast.makeText(getBaseContext(), "ImageCaptured",Toast.LENGTH_LONG).show();
Uri chosenImageUri = data.getData();
Bitmap mBitmap = null;
try {
mBitmap = Media.getBitmap(this.getContentResolver(),chosenImageUri);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ImageView img = new ImageView(this);
img.setImageBitmap(mBitmap);
setContentView(img);
}
}
}
When I execute this class . After capturing image through camera and clicking "ok" I am getting null pointer exception at the statement
"Uri chosenImageUri = data.getData();"
The Camera Application will not work in emulator with 2.2 Version. Try with 2.1 or less. Its working fine.
Resize the image before set on the image view solve your problem ....
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;
Matrix matrix = new Matrix();`enter code here`
// 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;
}

Categories

Resources