How To Move Image Captured With The Phone Camera From One Activity To An Image View In Another Activity?
Solution 1:
Here are my solution, I have tested in my environment. Hope this helps!
If using emulator to test, make sure camera supported like this
UPDATE WIH FULL SOURCE CODE (NEW PROJECT):
MainActivity.java:
package com.example.photocapture;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
publicclassMainActivityextendsActivity {
private Uri mFileUri;
privatefinalContextmContext=this;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intentintent=newIntent(MediaStore.ACTION_IMAGE_CAPTURE);
mFileUri = getOutputMediaFileUri(1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
// start the image capture Intent
startActivityForResult(intent, 100);
}
@OverrideprotectedvoidonActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
if (resultCode == RESULT_OK) {
if (mFileUri != null) {
StringmFilePath= mFileUri.toString();
if (mFilePath != null) {
Intentintent=newIntent(mContext, SecondActivity.class);
intent.putExtra("filepath", mFilePath);
startActivity(intent);
}
}
}
}
@OverridepublicbooleanonCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
returntrue;
}
@OverridepublicbooleanonOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.intid= item.getItemId();
//noinspection SimplifiableIfStatementif (id == R.id.action_settings) {
returntrue;
}
returnsuper.onOptionsItemSelected(item);
}
private Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
// Return image / videoprivatestatic File getOutputMediaFile(int type) {
// External sdcard locationFilemediaStorageDir=newFile(Environment.getExternalStorageDirectory(), "DCIM/Camera");
// Create the storage directory if it does not existif (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
returnnull;
}
}
// Create a media file nameStringtimeStamp=newSimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(newDate());
File mediaFile;
if (type == 1) { // image
mediaFile = newFile(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
} elseif (type == 2) { // video
mediaFile = newFile(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
} else {
returnnull;
}
return mediaFile;
}
}
SecondActivity.java:
package com.example.photocapture;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import java.io.File;
publicclassSecondActivityextendsActivity {
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intentintent= getIntent();
Stringfilepath= intent.getStringExtra("filepath");
BitmapFactory.Optionsoptions=newBitmapFactory.Options();
options.inSampleSize = 8; // down sizing image as it throws OutOfMemory Exception for larger images
filepath = filepath.replace("file://", ""); // remove to avoid BitmapFactory.decodeFile return nullFileimgFile=newFile(filepath);
if (imgFile.exists()) {
ImageViewimageView= (ImageView) findViewById(R.id.imageView);
Bitmapbitmap= BitmapFactory.decodeFile(imgFile.getAbsolutePath(), options);
imageView.setImageBitmap(bitmap);
}
}
@OverridepublicbooleanonCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_second, menu);
returntrue;
}
@OverridepublicbooleanonOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.intid= item.getItemId();
//noinspection SimplifiableIfStatementif (id == R.id.action_settings) {
returntrue;
}
returnsuper.onOptionsItemSelected(item);
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView android:text="@string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
activity_second.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.example.photocapture.SecondActivity">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?><manifestxmlns:android="http://schemas.android.com/apk/res/android"package="com.example.photocapture" ><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activityandroid:name=".MainActivity"android:label="@string/app_name" ><intent-filter><actionandroid:name="android.intent.action.MAIN" /><categoryandroid:name="android.intent.category.LAUNCHER" /></intent-filter></activity><activityandroid:name=".SecondActivity"android:label="@string/title_activity_second" ></activity></application></manifest>
END OF NEW PROJECT
------------------
FirstActivity:
private final Context mContext = this;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
buttonCapturePicture.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View v) {
captureImage();
}
});
}
@OverrideprotectedvoidonActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
if (resultCode == RESULT_OK) {
if (mFileUri != null) {
mFilePath = mFileUri.toString();
if (mFilePath != null) {
Intent intent = newIntent(mContext, SecondActivity.class);
intent.putExtra("filepath", mFilePath);
startActivity(intent);
}
}
}
// refresh phone's folder contentsendBroadcast(newIntent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
privatevoidcaptureImage() {
Intent intent = newIntent(MediaStore.ACTION_IMAGE_CAPTURE);
mFileUri = getOutputMediaFileUri(1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
// start the image capture IntentstartActivityForResult(intent, 100);
}
privateUrigetOutputMediaFileUri(int type) {
returnUri.fromFile(getOutputMediaFile(type));
}
privatestaticFilegetOutputMediaFile(int type) {
// External sdcard locationFile mediaStorageDir = newFile(Environment.getExternalStorageDirectory(), "DCIM/Camera");
// Create the storage directory if it does not existif (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
returnnull;
}
}
// Create a media file nameString timeStamp = newSimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(newDate());
File mediaFile;
if (type == 1) {
mediaFile = newFile(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
} elseif (type == 2) {
mediaFile = newFile(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
} else {
returnnull;
}
return mediaFile;
}
SecondActivity:
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.addContentView(R.layout.activity_second);
Intentintent= getIntent();
mFilePath = intent.getStringExtra("filepath");
previewMedia();
...
}
privatevoidpreviewMedia() {
BitmapFactory.Optionsoptions=newBitmapFactory.Options();
options.inSampleSize = 8; // down sizing image as it throws OutOfMemory Exception for larger images
mFilePath = mFilePath.replace("file://", ""); // remove to avoid BitmapFactory.decodeFile return nullFileimgFile=newFile(mFilePath);
if (imgFile.exists()) {
finalBitmapbitmap= BitmapFactory.decodeFile(imgFile.getAbsolutePath(), options);
mImagePreview.setImageBitmap(bitmap);
}
}
Solution 2:
there are several ways to do accomplish this, via sending the bitmap
itself within Intent
(Not Recommended) or you save the image to the storage and send its path within the intent
which is recommended.
first you save the image to the SDCARD
and then pass it within the intent
for example
Intentintent=newIntent(this,MyClass.class);
Bundlebundle=newBundle();
bundle.putString("IMAGE_PATH",imageFile);
intent.putExtras(bundle);
startActivity(intent);
and then in the other activity you could use
Stringpath= getIntent().getExtras().getString("IMAGE_PATH");
Bitmapbmp= BitmapFactory.decodeFile(path);
myImage.setImageBitmap(bmp);
Solution 3:
Refer to this link. You should save your image on a file and get the file path of that image. You can then pass the image path to the second activity.
Post a Comment for "How To Move Image Captured With The Phone Camera From One Activity To An Image View In Another Activity?"