Trying to display image taken from camera intent - java

I'm Currently trying to take a photo from the default camera intent from the MainActivity and then put that image in an ImageView in the same activity.
I'm saving the images such that the image taken overwrites the previously taken image (In this case, I call the image test.jpg and I store it in sdcard)
The problem I have with my code right now is the ImageView displays the photo taken the previous time the application ran.
Here is my code.
public class MainActivity extends Activity
{
ImageView imv;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imv = (ImageView)findViewById(R.id.imv);
Uri uri = null;
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/test.jpg";
try
{
uri = takePhoto(path);
}
catch(Exception e)
{
e.printStackTrace();
}
imv.setImageURI(uri);
}
private Uri takePhoto(String path) throws IOException
{
File photo = new File(path);
photo.createNewFile();
Uri fileUri = Uri.fromFile(photo);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, 0);
fileUri = Uri.fromFile(new File(path));
return fileUri;
}
}

Try to set image in onActivityResult as below:
protected void onActivityResult(int requestCode, int resultCode, Intent ata)
{
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
imv = (ImageView)findViewById(R.id.imv);
Bitmap photo = (Bitmap) data.getExtras().get("data");
imv.setImageBitmap(photo);
}}}

private static final int PICK_CONTACT_REQUEST = 0 ;
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == PICK_CONTACT_REQUEST) {
if (resultCode == RESULT_OK) {
imv.setImageURI(uri);
}
}
}
Set the image in onactivity result it will show new Image taken from the camera .

Try this,
private Uri takePhoto(String path) throws IOException
{
File photo = new File(path);
photo.createNewFile();
if(photo.exists())
photo.delete();
photo = new File(path);
Uri fileUri = Uri.fromFile(photo);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, 0);
fileUri = Uri.fromFile(new File(path));
return fileUri;
}

Related

Issue converting Image Uri from gallery to bitmap Android

I am having trouble converting from an image uri to a bitmap to then show it in an image view, yet I am getting an unhandled exception when converting into a bitmap.
Here is the code:
public class MainActivity extends AppCompatActivity {
public static final int PICK_IMAGE = 1;
Image picture = new Image();
Context context = getApplicationContext();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnGallery = (Button) findViewById(R.id.btnGallery);
final ImageView imageView = (ImageView) findViewById(R.id.imageView);
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
Uri imageUri = intent.getData();
Bitmap bitmap= MediaStore.Images.Media.getBitmap(context.getContentResolver(), imageUri);
imageView.setImageBitmap(bitmap);
}});
You are not picking the image on right way. Remove these three lines of code from you onClick method you will move them inside onActivityResult:
Uri imageUri = intent.getData();
Bitmap bitmap =
MediaStore.Images.Media.getBitmap(context.getContentResolver(), imageUri);
imageView.setImageBitmap(bitmap);
Then in your (probably) Activity override onActivityResult and do inside something like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null) {
Uri imageUri = data.getData();
try {
Bitmap bitmap =
MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Please try this code, this is working for my app.
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void takePhotoFromCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
// path = saveImage(bitmap);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(thumbnail);
path = saveImage(thumbnail);
}
}
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}

Issues in Camera Intent and image passing

I have an activity in which i open camera in surface view and capture a image.The captured is shown on the next activity of the image view.but result activity shows a white screen data not passing into result activity Please tell me the code how i pass image to next activity?
public class MainActivity extends AppCompatActivity
{
int REQUEST_IMAGE_CAPTURE = 1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void takePicture(View v) {
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)
{
if (resultCode == RESULT_OK)
{
Intent i = new Intent(this,Result.class);
i.putExtra("filepath",1);
startActivity(i);
}
}
}
}
Result Activity
public class Result extends Activity
{
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image);
iv = (ImageView)findViewById(R.id.imageView);
Bundle extras = getIntent().getExtras();
Bitmap bmp = (Bitmap) extras.getParcelable("filepath");
iv.setImageBitmap(bmp);
}
}
change this i.putExtra("filepath",yourfilepath);
and get it in next Activity..
Intent intent=getIntent();
String filepath=intent.getStringExtra("filepath");
Decode it in bitmap..
File sd = Environment.getExternalStorageDirectory();
File image = new File(sd+filePath, imageName);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);
imageView.setImageBitmap(bitmap);
Additionally you can get imagepath here..
In onActivityResult(...){
Bitmap photo = (Bitmap) data.getExtras().get("data");
Uri tempUri = getImageUri(getApplicationContext(), photo);
// CALL THIS METHOD TO GET THE ACTUAL PATH
String finalpath =getRealPathFromURI(tempUri)
//now you can putextra here
Here is the methods.
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = 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);
}

MediaStore.EXTRA_OUTPUT renders data null, other way to save photos?

Google offers this versatile code for taking photos via an intent:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
The problem is that if you're like me and you want to pass the photos as extras, using EXTRA_OUTPUT seemingly runs off with the photo data and makes subsequent actions think the intent data is null.
It appears this is a big bug with Android.
I'm trying to take a photo then display it as a thumbnail in a new view. I'd like to have it saved as a full sized image in the user's gallery. Does anyone know a way to specify the image location without using EXTRA_OUTPUT?
Here's what I have currently:
public void takePhoto(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
// takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
#SuppressLint("SimpleDateFormat")
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "JoshuaTree");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("JoshuaTree", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
handleSmallCameraPhoto(data);
}
}
}
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
Intent displayIntent = new Intent(this, DisplayPhotoActivity.class);
displayIntent.putExtra("BitmapImage", mImageBitmap);
startActivity(displayIntent);
}
}
If you specified MediaStore.EXTRA_OUTPUT, the image taken will be written to that path, and no data will given to onActivityResult. You can read the image from what you specified.
See another solved same question here: Android Camera : data intent returns null
Basically, there are two ways to retrieve the image from Camera, if you use to send a captured image through intent extras you cannot retrieve it on ActivityResult on intent.getData() ' because it saves the image data through extras.
So the idea is:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
And retrieving it on ActivityResults checking the retrieved intent:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == RESULT_OK) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (intent.getData() != null) {
ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(intent.getData(), "r"); 
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
} else {
Bitmap imageRetrieved = (Bitmap) intent.getExtras().get("data");
}
}
}
}
Here is how you can achieve what you want:
public void onClick(View v)
{
switch(v.getId())
{
case R.id.iBCamera:
File image = new File(appFolderCheckandCreate(), "img" + getTimeStamp() + ".jpg");
Uri uriSavedImage = Uri.fromFile(image);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
i.putExtra("return-data", true);
startActivityForResult(i, CAMERA_RESULT);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
case CAMERA_RESULT:
if(resultCode==RESULT_OK)
{
handleSmallCameraPhoto(uriSavedImage);
}
break;
}
}
private void handleSmallCameraPhoto(Uri uri)
{
Bitmap bmp=null;
try {
bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
Intent displayIntent = new Intent(this, DisplayPhotoActivity.class);
displayIntent.putExtra("BitmapImage", bmp);
startActivity(displayIntent);
}
private String appFolderCheckandCreate(){
String appFolderPath="";
File externalStorage = Environment.getExternalStorageDirectory();
if (externalStorage.canWrite())
{
appFolderPath = externalStorage.getAbsolutePath() + "/MyApp";
File dir = new File(appFolderPath);
if (!dir.exists())
{
dir.mkdirs();
}
}
else
{
showToast(" Storage media not found or is full ! ");
}
return appFolderPath;
}
private String getTimeStamp() {
final long timestamp = new Date().getTime();
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
final String timeString = new SimpleDateFormat("HH_mm_ss_SSS").format(cal.getTime());
return timeString;
}
Edit:
Add these to Manifest:
Starting Api 19 and above READ_EXTERNAL_STORAGE should be declared explicitly
*<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />*
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
to you manifest.
Try this one android.provider.MediaStore.EXTRA_OUTPUT hope will solve your bug. The following code works for me:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
I was facing same problem, every time getting null while retrieving data on other activity with getIntent().getData() then solved by writting complete android.provider.MediaStore.EXTRA_OUTPUT this solved my bug.

Using the camera intent to take a picture without an sdcard

I'm having trouble using the camera when there's no sdcard present.
When there is an sdcard, using the camera is trivial, e.g.
http://www.vogella.com/articles/AndroidCamera/article.html + a plethora of other examples.
However, I need to make my app available to devices which don't have SD cards, (e.g. the Sony Xperia series.) I've tried modifying the code such that I'm using the internal storage (I think):
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(getDir("myDirec", Context.MODE_WORLD_WRITEABLE), "tmp_photo_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
file.createNewFile();
mImageCaptureUri = Uri.fromFile(file);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
However, upon result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intentReturn) {
if (resultCode != RESULT_OK)
return;
String path = mImageCaptureUri.getPath();
Bitmap bitmap = BitmapFactory.decodeFile(path);
...
bitmap is null.
Which leads me to believe that there's some permissions issue....maybe?
I've tried some of the other internal storage options, http://developer.android.com/guide/topics/data/data-storage.html#filesInternal e.g. getFilesDir() but the same result: null bitmap.
Has anyone had any success in using the camera without an sdcard?
Try this. It works..
private Uri imageUri;
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.btnImageCapture:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File dir = context.getDir("directory", Context.MODE_PRIVATE);
File photo = new File(dir, "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, OPEN_CAMERA);
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case OPEN_CAMERA:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.ImageView);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
}
}
}
}

capturing image using camera in Android

Hi stackoverflow friends,
I need to take a picture using camera and after takin the picture go to next activity without showing the first activity. And display it in an imageview.
Below is the flow of my application
first activity-> there is button for camera intent->go to the next activity(without showing the fist activity) second activity->there i need to show the image in imageview.
I saw a lot of examples of camera intent nobody explains how to go to the next activity without showing the first and display it in imageview of second.
Any outofmemeory problem occurs while displaying images in imageview repeatedly?
Thanks in advance
In First activity :
Button b=(Button)findViewByid(R.id.button);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
doTakePhotoAction();
}
});
private void doTakePhotoAction() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"pic_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, CAMERA_RESULT);
// finish();
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == CAMERA_RESULT) {
Intent intent = new Intent(this, nextimage.class);
// here you have to pass absolute path to your file
intent.putExtra("image-path", mUri.getPath());
intent.putExtra("scale", true);
startActivity(intent);
finish();
}
}
In nextimage.class you can set one image view and get the imagepath from putExtra and place it in imageview.
String mImagePath = extras.getString("image-path");
Bitmap mBitmap = getBitmap(mImagePath);
private Uri getImageUri(String path) {
return Uri.fromFile(new File(path));
}
private Bitmap getBitmap(String path) {
Uri uri = getImageUri(path);
InputStream in = null;
try {
in = mContentResolver.openInputStream(uri);
return BitmapFactory.decodeStream(in);
} catch (FileNotFoundException e) {
Log.e(TAG, "file " + path + " not found");
}
return null;
}
place the bitmap in the imageview.you have to create imageview in secondActivity.
use a camera intent....here's a simple code
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;
public class CameraIntent extends Activity {
final static int CAMERA_RESULT = 0;
ImageView imv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_RESULT);
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK)
{
Get Bundle extras = intent.getExtras();
Bitmap bmp = (Bitmap) extras.get("data");
imv = (ImageView) findViewById(R.id.ReturnedImageView);
imv.setImageBitmap(bmp);
}
}
}
Use Following Code for that, it will solve your problem.
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
onActivityResult() Method:-
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_PIC_REQUEST) {
bmpImage = (Bitmap) data.getExtras().get("data");
drawable = new BitmapDrawable(bmpImage);
mImageview.setImageDrawable(drawable);
}
}
}

Categories

Resources