Show selected image in another activity - java

I've searched on stackoverflow but never found a solution
Here is my situation:
I have a button which start an intent to pick an image
How can I resize proportionally (to keep the aspect ration) and display it on another activity (in imageview)?
I also want to save this resized image to user storage. How can I do that?
Thanks!
Here is my code
MainActivity.java
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, getString(R.string.completeaction)),
PICK_FROM_FILE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap selectedphoto = null;
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RequestExternal && 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 filePath = cursor.getString(columnIndex);
selectedphoto = BitmapFactory.decodeFile(filePath);
cursor.close();
Intent intent = new Intent(MainActivity.this,PhotoResized.class);
intent.putExtra("data", selectedphoto);
startActivity(intent);
}
}
PhotoResized.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photoresized);
img = (ImageView) findViewById(R.id.imageView1);
}

For resizing the image use sampling technique provided by dev.android here
Use Lrucache for storing images. Use technique shown here

Related

How to pass image gotten from camera or gallery to another activity

1. User selects a button to either upload from gallery or capture from camera
From gallery
choose_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
// Sets the type as image/*. This ensures only components of type image are selected
intent.setType("image/*");
//We pass an extra array with the accepted mime types. This will ensure only components with these MIME types as targeted.
String[] mimeTypes = {"image/jpeg", "image/png"};
intent.putExtra(Intent.EXTRA_MIME_TYPES,mimeTypes);
// Launching the Intent
startActivityForResult(intent,1);
}
});
From camera
capture_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(UploadActivity2.this, BuildConfig.APPLICATION_ID + ".provider", createImageFile()));
startActivityForResult(intent, 0);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
2. User selects a photo from gallery or capture from camera and the image is displayed in the current activity
public void onActivityResult(int requestCode,int resultCode,Intent data){
............//grant permission codes here
//If it is from gallery
if (requestCode == 1 && 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 imgDecodableString = cursor.getString(columnIndex);
cursor.close();
//Display image with glide
Glide.with(this).asBitmap().load(imgDecodableString).into(new CustomTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<?
super Bitmap> transition) {
display_image.setImageBitmap(resource);
display_image.setVisibility(View.VISIBLE);
}
}
//If request is from camera
if (resultCode == Activity.RESULT_OK)
switch (requestCode){
case 0:
//Display image in current activity
Glide.with(this)
.load(cameraFilePath)
.into(display_image);
/*display_image.setImageURI(Uri.parse(cameraFilePath));*/
display_image.setVisibility(View.VISIBLE);
break;
}
}
3. I have a 'NEXT' button and when clicked I want to transfer the image displayed (Gotten from either the Gallery or Camera) to another activity, I havn't written a code for passing the image yet
next_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UploadActivity2.this, UploadActivity3.class);
startActivity(intent);
}
});
4. I want to know the best way to do this without affecting image quality and memory because in the next activity (UploadAcitivity3), I will be uploading the image passed to the server and saving in a directory
Please follow the steps to achieve this:
Option - 1: If you want to pass multiple images then use below:
Step - 1: Store the selected images path in an ArrayList like below:
private ArrayList<String> selectedImages = new ArrayList<>();
public void onActivityResult(int requestCode,int resultCode,Intent data) {
............//grant permission codes here
//If it is from gallery
if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
....
String imgDecodableString = cursor.getString(columnIndex);
selectedImages.add(imgDecodableString);
}
//If request is from camera
if (resultCode == Activity.RESULT_OK) {
selectedImages.add(cameraFilePath);
}
}
Step - 2: From onClick set the selected images list as extras to intent
next_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UploadActivity2.this, UploadActivity3.class);
intent.putStringArrayListExtra("SELECTED_IMAGES", selectedImages);
startActivity(intent);
}
});
Step - 3: Retrieve the selected images from intent in UploadActivity3 like below:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
....
ArrayList<String> selectedImages = getIntent().getStringArrayListExtra("SELECTED_IMAGES");
}
Option - 2: If you want to pass single image then use below:
Step - 1: Store the selected image path like below:
private String selectedImage;
public void onActivityResult(int requestCode,int resultCode,Intent data) {
............//grant permission codes here
//If it is from gallery
if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
....
String imgDecodableString = cursor.getString(columnIndex);
selectedImage = imgDecodableString;
}
//If request is from camera
if (resultCode == Activity.RESULT_OK) {
selectedImage = cameraFilePath;
}
}
Step - 2: From onClick set the selected images list as extras to intent
next_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UploadActivity2.this, UploadActivity3.class);
intent.putExtra("SELECTED_IMAGE", selectedImage);
startActivity(intent);
}
});
Step - 3: Retrieve the selected images from intent in UploadActivity3 like below:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
....
String selectedImage = getIntent().getStringExtra("SELECTED_IMAGE");
Glide.with(this).load(selectedImage).into(image_view);
}
You can send the image path through Intent
next_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UploadActivity2.this, UploadActivity3.class);
intent.putExtra("path", imagePath);
startActivity(intent);
}
});
You already have image path for capturing image is cameraFilePath
and for gallery image imgDecodableString.
Declare String imagePath; as class variable and assign them in onActivityResult.
imagePath = imgDecodableString;//For Gallery
imagePath = cameraFilePath;//For Capture image
Receive path in UploadActivity3.class
String imagePath = getIntent().getStringExtra("path");
Use this path in second activity as you want.

API 25 Image capturing

i was building my app on API level 23 ,then i have changed API level to 25 the same code is not working now , here's my code :
public class expert extends Activity implements View.OnClickListener {
Button btnsetwall;
ImageButton imgbtntakeph;
ImageView Imview;
static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_expert);
Imview = (ImageView) findViewById(R.id.imageView22);
btnsetwall = (Button) findViewById(R.id.button2);
btnsetwall.setOnClickListener(this);
}
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
Imview.setImageBitmap(imageBitmap);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), imageBitmap);
// CALL THIS METHOD TO GET THE ACTUAL PATH
Toast.makeText(getBaseContext(),"Here "+ getRealPathFromURI(tempUri), Toast.LENGTH_LONG).show();
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
when i try to pick image from gallery or to get captured image my app crashes and i get UriString Exception
can any one tell the reason ?? and how to solve !
thanks in advance

Issue in fetching image from SD card and displaying on an ImageView

I found a program on this page to fetch image from sd card and show it on an imageView. I am getting issue at this line -
bitmap = BitmapFactory.decodeFile(picturePath);
I am getting correct value of picturePath variable but in the above line it is setting bitmap value as null. I had visited various threads and almost everyone is using this same line. I am not getting what is wrong with my code
Here is my complete code -
private Button upload;
ImageView imgView;
EditText caption;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgView = (ImageView) findViewById(R.id.imageView);
upload = (Button) findViewById(R.id.Upload);
caption = (EditText) findViewById(R.id.caption);
imgView.setImageResource(R.drawable.ic_menu_gallery);
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 2);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2 && 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 = BitmapFactory.decodeFile(picturePath);
imgView.setImageBitmap(bitmap);
caption.setText("Hello");
}
}
Try putting this in your AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
After that, make sure you have the permission enabled in the App Info screen on your device.

Select a image from the gallery and show it in another Activity

I am making an android application in which i have to select image from gallery by clicking a button and then display it in another activity with two text fields, the problem is i am able to open the gallery and select image from it but i am not able to display image in another activity...
here is my code...
PictureOptions.java
public void buttonGalleryOpen(View view)
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap selectedphoto = null;
super.onActivityResult(requestCode, resultCode, 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 filePath = cursor.getString(columnIndex);
selectedphoto = BitmapFactory.decodeFile(filePath);
cursor.close();
Intent intent = new Intent(PictureOptions.this,ShowImage.class);
intent.putExtra("data", selectedphoto);
startActivity(intent);
}
PictureOptions.xml
<Button
android:id="#+id/buttonGalleryOpen"
android:layout_width="fill_parent"
android:layout_height="66dp"
android:layout_weight="0.34"
android:onClick="buttonGalleryOpen"
android:text="#string/button_gallery_open" />
ShowImage.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_image);
ImageView imageview = (ImageView)findViewById(R.id.ImageShow);
Bitmap selectedphoto =(Bitmap)this.getIntent().getParcelableExtra("data");
imageview.setImageBitmap(selectedphoto);
}
ShowImage.xml
<ImageView
android:id="#+id/ImageShow"
android:layout_width="200dp"
android:layout_height="200dp" />
All things are working fine and second activity(ShowImage) is also opening except that no iamge is displying....dont know why..?HELP
This line in your code does not make sense:
intent.putExtra("data", "selectedphoto");
You are adding here string "selectedphoto" which is in no way connected to selectedphoto variable you initialised earlier. You could put your bitmap to intent extra as byte array but this is inefficient, especially when the image is large.
Instead of passing bitmap to ShowImage activity, pass your URI and then retrieve actual bitmap in ShowImage activity exactly as you do now in your PictureOptions activity.
intent.setData( uri );
In your ShowImage activity do:
URI imageUri = getIntent().getData();
Yo have a typo in intent.putExtra("data", "selectedphoto");, you are passing a String not the bitmap. Change it in
Intent intent = new Intent(PictureOptions.this,ShowImage.class);
intent.putExtra("data", selectedphoto);
startActivity(intent);
removing the double quote from selectedphoto
private void selectImage() {
final CharSequence[] items = { "Photo Library", "Camera", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select");
Utils.hideSoftKeyboard(getActivity());
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Camera")) {
// camera intent
} else if (items[item].equals("Photo Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
String tempPath = getPath(selectedImageUri, getActivity());
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(tempPath, btmapOptions);
resized = Bitmap.createScaledBitmap(bitmap,
(int) (bitmap.getWidth() * 0.8),
(int) (bitmap.getHeight() * 0.8), true);
profileEditImageView.setImageBitmap(resized);
}
}
}
public String getPath(Uri uri, Activity activity) {
String[] projection = { MediaColumns.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = activity
.managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

save path of image imported from gallery into sql database and display it in an imageview later

I'm trying to save the path of an image imported from the gallery using this method:
case R.id.media:
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
return true;
Here is the on activity result method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
final 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();
mImage = picturePath;
ImageView imageView = (ImageView) findViewById(R.id.note_image);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
imageView.setClickable(true);
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewImageIntent = new Intent(android.content.Intent.ACTION_VIEW, selectedImage);
startActivity(viewImageIntent);
}
});
}
}
And here is the populate field method:
mImage =(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_IMAGE)));
But this is not working, the path doesnt get saved and when i close the activity and start the activity again, the image is gone. How can i fix this?

Categories