Android Display Camera Image In New Activity - android

So far I have my app taking a picture creating a new folder on the SD Card and saving the pictuers into the new folder.
I'm trying to get it so once the picture has been took it will display in a new Activity with two buttons that say "Use" or "Retake". So far the image saving is working perfectly fine but once the image has been took and it tries to open the new Activity it just stays on the camera Activity and shows the image which I cant use as it has a surfaceView onit.
In my LogCat I get the error "Oh, no reference" which is set to show if it can't find the picture, which is why im thinking it may be because I am not calling the picture from the correct place in my Punch.java.
So basiclly I am trying to once an image has been took the app to open a New Activity "Punch.java" and display the image that has just been took.
UPDATE Thanks to Lumis (code below has been updated)
Changed
intent.putExtra("filepath",uriSavedImage);
to
intent.putExtra("filepath",uriSavedImage.toString());
Which now opens the new Activity but still cannot see the image.
UPDATE 2 Punch.java
I have updated my Punch.java as with the new code if i change (myRef) to "/sdcard/Punch/image_0.jpg" I can see that image but I need it to referance to the image that was just taken with the camera which is something to do with this line I think intent.putExtra("filepath",uriSavedImage.toString());
Update 3
Nearly working perfectly now using intent.putExtra("filepath",Uri.parse(output.getAbsolutePath()).toString()); but for some reason it is still putting mnt/sdcard at the start it just needs to be sdcard/
Ok now working fine /mnt/sdcard is when the sdcard was mounted to the computer while i took the picture.
In my Camera Activity I have
PictureCallback myPictureCallback_JPG = new PictureCallback(){
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
/*Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(arg0, 0, arg0.length); */
int imageNum = 0;
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Punch");
imagesFolder.mkdirs(); // <----
String fileName = "image_" + String.valueOf(imageNum) + ".jpg";
File output = new File(imagesFolder, fileName);
while (output.exists()){
imageNum++;
fileName = "image_" + String.valueOf(imageNum) + ".jpg";
output = new File(imagesFolder, fileName);
}
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(AndroidCamera.this,
"Image saved",
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(getBaseContext(), Punch.class);
intent.putExtra("filepath",uriSavedImage.toString());
//just using a request code of zero
int request=0;
startActivityForResult(intent,request);
}};
And my Punch.java which is the next Activity is:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.punch);
String myRef = this.getIntent().getStringExtra("filepath");
File imgFile = new File(myRef);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imagepunch);
myImage.setImageBitmap(myBitmap);
}
}
}

I think it is the file path issue. You submitted your file path as URI but you are reading it in the viewer activity as a string.
Perhaps you neet to change this line into:
intent.putExtra("filepath",uriSavedImage.toString());
Or
intent.putExtra("filepath",Uri.parse(output.getAbsolutePath()).toString());
Different version of android may not work the same when it comes to file path, so you need to experiment using Uri.parse(fileStr) or String...

Just looking at your code and your approach, I think what you would typically see in this scenario is a new content handler registered so that it appears under the "Share" option of the camera / image library. This way, you are not getting involved in the use/retake logic which is essentially redundant for built-in Android functionality. Think of an app like Evernote or Picasa. You take a picture (or look one up that you took previously) and select "Share". One of the Share options, along with Picasa, Email, etc would be your app. That is how I would do it.

Related

passing high resolution images from one activity to other

I'm creating an image filter app in Android studio. first, the user selects an image from gallery and it will be displayed in imageview. Then the user clicks edit button and that image is displayed in imageview of next activity where we can add filters... It works fine with low resolution images but when I select any high resolution image it is shown in first imageview but when I click edit button either the app crashes or the last image I had selected is displayed.I searched for the solution but couldn't find it. If anyone knows how to solve this problem please help me
There is a limit to the size of data that can be passed through an intent. The limit is roughly 500Kb - your high resolution photographs will be larger than this.
Consider saving your image to a file location on the device, passing the URI to the receiving activity and loading it within there.
first paste crash logs.
then instead of passing image itself just pass image path.
or simply add the edit tools and mainView in one activity and make edit tools invisible! however you can use fragment too.
use with putExtra to send the Uri Path:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent .setClass(ThisActivity.this, NewActivity.class);
intent .putExtra("KEY", Uri);
startActivity(intent );
You just need to add path of image.
It's better to save the image in storage and pass the Uri of location instead of passing the image.
Save image in storage:-
public static Uri saveImageOnExternalStorage(Bitmap capturedBitmap, String imageId) {
if (null != capturedBitmap ) {
OutputStream fOutputStream;
String path = Environment.getExternalStorageDirectory().toString();
File file = new File(path + "temp", mediaId + ".png");
file.delete();
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
try {
if (file.createNewFile()) {
fOutputStream = new FileOutputStream(file);
capturedBitmap.compress(COMPRESS_FORMAT, 100, fOutputStream);
fOutputStream.flush();
fOutputStream.close();
return Uri.fromFile(file); // return saved image path on external storage
}
} catch (FileNotFoundException e) {
Log.e(TAG,e.getMessage());
return null;
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG,e.getMessage());
}
}
return null;
}
Now the same Uri you can pass in the intent of next activity:-
Intent intent = new Intent(CurrentActivity.this, LaunchActivity.class);
intent .putExtra("image_key", Uri);
startActivity(intent );

how to use a bitmap taken by the camera through multiple activities in android?

I am making a photo app in which in the first activity the user takes a picture (he can see the picture in the ImageView), in the second activity he chooses with who to share the image,and in the 3rd activity he should be able to see the image again in a different ImageView than the first to add some data. I know how to move the bitmap from one activity to the next one by an intent, but how to do it if i want to send it to the 3rd activity of my user path? If i startActivity(intent) it will skip my second activity and if i don´t put it the 3rd activity is showing me an empty ImageView.. Can someone please help me in telling me ways of how to automatically load (without user interaction) this picture in the 1st and 3rd activity and some example?
I already being reading posts about how to convert to Base64 and load again, but their examples are using images already in the memory of the phone and in my case are pictures that were just taken by the user, so in principle i don´t know the name of the image file..
Thank a lot!
Add This Image In Your Custome Catch Folder
Like Make Your Folder in External or Internal Storage
Then Save Image that will capture by camera inside That Folder..
public static void SaveImagecatch(Bitmap finalBitmap) throws IOException {
File Folder = new File(Environment.getExternalStorageDirectory() + "/data/Catch");
if (Folder.mkdir()) {
nomediaFile = new File(Environment.getExternalStorageDirectory() + "/data/Catch/" + NOMEDIA);
if (!nomediaFile.exists()) {
nomediaFile.createNewFile();
}
}
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/data/Catch");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
Catch_uri = Uri.parse("file://" + myDir + "/" + fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
Log.e("yes", "yes");
} catch (Exception e) {
e.printStackTrace();
Log.e("no", "no");
}
}
Then.. get Image From Uri path of Your saved Image.
Uri imageUri = Catch_uri;
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageUri);
Imageview my_img_view = (Imageview ) findViewById (R.id.my_img_view);
my_img_view.setImageBitmap(bitmap);
This is Worked For Me.. I Hope This Will be Helpfull to you
Actually in second activity, you need to get Intent from first activity and do your work and then create new Intent and put your image into it, finally start third activity using new intent.
in second activity:
Intent firstToSecodeIntent = getIntent();
// some codes
Intent secondToThirdIntent = new Intent(this, ThirdActivity.class);
Intent.putExtra("image", /*your Image object*/);
startActivity(secondToThirdIntent);
in third activity:
Intent secondToThirdIntent = getIntent();
// get your image and set it into your imageView

Images not being saved when picture is taken by camera app that isn't the stock camera

I'm currently trying to save images taken from a phone to its gallery, but the code below only works if I choose the stock camera app when the chooser dialog pops up. Whenever I choose another camera app(e.g., the Google camera), the taken picture doesn't get saved any where.
To make things even stranger, sometimes the picture does show up in its designated directory in the gallery, but after 15 mins or so, the same goes for when I use the stock camera app: the picture will get saved in the default camera shots directory, but takes quite a bit to show up in its designated directory, if it shows up there at all.
// Capturing Camera Image will launch camera app request image capture
void captureImage() {
//file uri to store image.
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
// Request camera app to capture image
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
getActivity().startActivityForResult(captureIntent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
well ,
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
does not work anymore .
you should do something like this :
call Camera Activity :
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
and onActivityResult :
if (data.getData() == null) {
Bitmap bm = (Bitmap)
data.getExtras().get("data");
String timeStamp = new SimpleDateFormat(
"yyyyMMdd_HHmmss").format(new Date());
File pictureFile = new File(Environment
.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
.getAbsolutePath()
+ File.separator + "IMG_" + timeStamp);
try {
FileOutputStream fos = new FileOutputStream(
pictureFile);
bm.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
String filePath = pictureFile.getAbsolutePath();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} } else {
Uri imgUri =data.getData());
}
It turns out my code was working after all. The pictures were being saved in the new directory, but the problem was that the gallery wasn't being updated, which explains why the photos would randomly appear in the directory later on. Being new to this, it never occurred to me that I would have to update the gallery. I only came to this realization after using ES File Explorer to look through my files. To fix my problem, I just made a new method in my CameraFragment that would call on the media scanner. I called this method from onActivityResult().
Here's the new method, though there's nothing really "new" about it since I ran into the same code on other SO questions:
protected void mediaScan() {
getActivity().sendBroadcast(
new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.parse(fileUri.toString())));
}
I also don't need to call the package manager and iterate through the apps that could handle the camera intent if I'm not giving the option to use choose a picture from a gallery, so I'm going to remove all that from my question.

Android change photo orientation for upload

I have found lots of solution to change photo orientation for DISPLAY, and succeeded. But now I need to upload that photo by using file.path. Is there anyway to directly change the photo orientation but not just display differently?
CustomMultiPartEntity multipartContent = new CustomMultiPartEntity(
new CustomMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
Constant.Process = (int) ((num / (float) totalSize11) * 100);}
});
multipartContent.addPart("key", new StringBody(Constant.Key));
multipartContent.addPart("userfile", new FileBody(new File(up.FilePath)));
httpPost.setEntity(multipartContent);
HttpResponse response1 = httpClient.execute(httpPost, httpContext);
response = EntityUtils.toString(response1.getEntity());
Something like that, I need to insert a FileBody by a FilePath into that 'multipartContent', then upload, is there anyway to upload a correct orientation photo??
Thank you very much!
EDIT: This is my onclick method to have camera, how can I add code to rotate image before it was saved?
public void onClick(View v) {
if (v == btn_camera) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newPicFile = "Miuzz"+ df.format(date) + ".jpg";
String outPath = "/sdcard/" + newPicFile;
File outFile = new File(outPath);
mUri = Uri.fromFile(outFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
startActivityForResult(cameraIntent, 1);
}
}
There is unfortunately no way of modifying the orientation of the photo file other other than to load the image, rotate it manually and re-save it in it's correct orientation.
See this question for some details on how to save the image once it's rotated: Android Rotate Picture before saving
Edit: Ok, so what you'll want to do is in your onActivityResult() method, load the image and rotate it as you already do. After rotating it, you should have a correctly orientated Bitmap object, then all you need to do is either overwrite your existing photo, or create a new file like this:
try {
FileOutputStream out = new FileOutputStream(filename);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Also worth noting, is that if you decide to create a new file, be sure to delete it after your upload is complete otherwise you'll be unnecessarily filling up the user's internal storage.

Pictures wont save on Samsung Nexus

I have a Problem. I start from my own Application the Build-In Photoapplication with a Photo-Intent.
String photoName = System.currentTimeMillis() + ".jpg";
File file = new File(getFilesDir(),//Environment.getExternalStoragePublicDirectory(
//Environment.DIRECTORY_DCIM),
photoName); // Anlegen der Datei im entsprechenden
// Verzeichnis
FileOutputStream fos = null;
try {
fos = openFileOutput(photoName, Context.MODE_WORLD_WRITEABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outputFileUri = Uri.fromFile(file);
intentPhoto.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
//startActivity(intentPhoto);
startActivityForResult(intentPhoto, TAKE_PICTURE);
This is my Code to start the Activity. As you can see, the first thing i do is to set up the file in the directory and then give the intent the location of the file to store it.
But everytime i take a picture it is not saved to the Pictures Directory. The only way to save the picture is to turn off the phone and restart it. Then every picture I have taken befor is there. This happens since the last updated to 4.1.1. Befor i updated the phone, everything worked fine, but since the update I have this problem.
Can somebody help me? Does anyone have the same Issue?
Make sure you offer the new file to be scanned:
MediaScannerConnection.scanFile(this,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
// code to execute when scanning is complete
}
});
You can pass in a null argument for the OnScanCompletedListener if you don't need to be notified when the scanner has picked it up, but you might want to at least put a logging statement there.
It works fine now, the problem was that I create the File by my self, with:
File file = new File(..);
But you have to use:
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "IMG_"+ timeStamp+.jpg");
And put it into the intent to save the file at once without restarting the phone.

Categories

Resources