So far I have my app taking a picture AndroidCamera.java using the camera and then saving the image and displaying it in a new Activity Punch.java which works fine. On this screen there are then two options too use the image or retake the image if the button retake is clicked it will go back to the AndroidCamera.java Activity and if use is clicked it will then go to the Activity BeatEmUp.java which is the new Activity I want to show the image on again.
I just cant figure out what to put in the BeatEmUp.java Activity to display the image again in this new Activity you can see on the code below that I am passing the string from AndroidCamera.java to Punch.java but don't think I can do this again from the Punch.java to BeatEmUp.java?
Update Adil Soomro
BeatEmUp.java Activity now force closes when Use button is clicked.
Ok code below has been updated I had to change intent.putExtra("filepath",imagePath);
to Use.putExtra("filepath",imagePath); as with intent at the start it was giving me an error I have also added the BeatEmUp.java as I am not sure if this is correct i thought it would just be the same code as I use to show the image on Punch.java
AndroidCamera.java
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",Uri.parse(output.getAbsolutePath()).toString());
//just using a request code of zero
int request=0;
startActivityForResult(intent,request);
}};
Punch.java
String imagePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.punch);
imagePath = this.getIntent().getStringExtra("filepath");
Button buse = (Button) findViewById(R.id.buse);
buse.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent Use = new Intent(Punch.this, BeatEmUp.class);
Use.putExtra("filepath",imagePath);
startActivity(Use);
}
});
Button bretake = (Button) findViewById(R.id.bretake);
bretake.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent Retake = new Intent(Punch.this, AndroidCamera.class);
startActivity(Retake);
}
});
String myRef = this.getIntent().getStringExtra("filepath");
File imgFile = new File(myRef);
Log.e(">>>", myRef);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imagepunch);
myImage.setImageBitmap(myBitmap);
}
}
}
BeatEmUp.java
String myRef = this.getIntent().getStringExtra("filepath");
File imgFile = new File(myRef);
Log.e(">>>", myRef);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imagepunch);
myImage.setImageBitmap(myBitmap);
Yes. You can pass that image URI again to next Activity.
You just need to store image path in class level variable in Punch.java class, and when starting BeatEmUp Activity, put that Image path again in the Intent and get it in BeatEmUp
Edit:
Take a class level String in Punch.java
String imagePath;
and inside onCreate()
imagePath = this.getIntent().getStringExtra("filepath");
and when starting BeatEmUp Activity
Intent Use = new Intent(Punch.this, BeatEmUp.class);
intent.putExtra("filepath",imagePath);
startActivity(Use);
Related
In My app I am taking picture and I am successfully saving it in the gallery after compressing it. Now I want to show it into other activity, so that user can share it or view it at least. So How can I do that.
Following is my code which is saving picture and just after saving it, it shows ad , and on the adClosed event I want to send that taken picture to other activity , How Can I do that. My code just goes like this ..
File storagePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator + "MyAnimals");
storagePath.mkdirs();
String finalName = Long.toString(System.currentTimeMillis());
//this snippet is saving image And I am showing ad after saving picture
File myImage = new File(storagePath, finalName + ".jpg");
String photoPath = Environment.getExternalStorageDirectory().getAbsolutePath() +"/" + finalName + ".jpg";
try {
FileOutputStream fos = new FileOutputStream(myImage);
newImage.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
//refreshing gallery
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(myImage));
sendBroadcast(mediaScanIntent);
} catch (IOException e) {
Toast.makeText(this, "Pic not saved", Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(this, "Pic saved in: " + photoPath, Toast.LENGTH_SHORT).show();
displayInterstitial();
interstitial.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
Log.v("Add time");
Intent intent = new Intent(CameraActivity.this,ShowCapturedImage.class);
//Now How to send the saved picture to the image view of other activity?
startActivity(intent);
super.onAdClosed();
}
});
1) put taken image path in intent
2) get path in other activity and set it in imageview
public static final int REQUEST_CODE_FROM_CAMERA = 112;
private Uri fileUri;
String image_path = "";
//Catch image from below function
private void fromCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
Log.d("FROM CAMERA CLICKED file uri", fileUri.getPath());
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, REQUEST_CODE_FROM_CAMERA);
}
//On Activity result store image path
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_FROM_CAMERA
&& resultCode == Activity.RESULT_OK) {
try {
image_path = fileUri.getPath();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
On Click of any button
Intent iSecond=new Intent(FirstActivity.this,SecondActivity.class);
iSecond.putExtra("image_path",image_path);
startActivity(iSecond);
In Second Activity onCreate()
Bundle extras = intent.getExtras();
if(extras != null)
String image_path = extras.getString("image_path");
From this image path , You can get image and set to imageview
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.imageView1);
File imgFile = new File("/storage/emulated/0/1426484497.png");
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
.getAbsolutePath());
iv.setImageBitmap(myBitmap);
}
}
You can do this by adding a ImageView to your Activity.
A simple ImageView should look like this:
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView" />
Then you capture it in your Activity class
ImageView imageView = (ImageView) this.findViewById(R.id.imageView);
Now the fun part. We'll capture your image using the image URI and parse it in a bitmap.
Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath()); //Here goes your image path
imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap,imageView.getWidth(), imageView.getHeight(), false)); //I scale the bitmap so it show properly. If the image is too big, it wont show on the ImageView
That should do the trick, tell me if it works!
In My Code The image is not open in ImageView from sdcard i already checked the permissions in 'manifest.xml'.
Same if i try to open it using static name then it will showed by ImageView but not dynamically.
Main Activity
private OnClickListener OnCapture = new OnClickListener() {
#Override
public void onClick(View v) {
String time = mCamUtils.clickPicture();
nextActivity = new Intent(MainActivity.this,EffectActivity.class);
nextActivity.putExtra("ImageName", time);
startActivity(nextActivity);
finish();
}
};
EffectActivity
public class EffectActivity extends Activity {
Intent getActivity = null;
ImageView image = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.effectactivity);
getActivity = getIntent();
String name = getActivity.getStringExtra("ImageName");
String path = Environment.getExternalStorageDirectory()+"/GalaxyPhoto/GX_" +name+ ".JPG";
Toast.makeText(getApplicationContext(), path, Toast.LENGTH_LONG).show();
image = (ImageView) findViewById(R.id.imageView1);
File f = new File(path);
byte[] b = new byte[(int)f.length()];
if(f.exists())
{
try
{
if(f.exists())
{
FileInputStream ff = new FileInputStream(f);
ff.read(b);
Bitmap g = BitmapFactory.decodeFile(path);
image.setImageBitmap(g);
ff.close();
}
else
{
Toast.makeText(getApplicationContext(), "ELSE", Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
}
}
}
}
I am trying to open image which i saved in before this activity and i catch the name of image here but that does not show the image.
String path = Environment.getExternalStorageDirectory()+"/GalaxyPhoto/GX_" +name+ ".JPG";
In this line try changing "JPG" into "jpg".i think your file extension might be in lowercase letter and it might say f.exists false.
Hope it will help.
String fname = "Pic-" + System.currentTimeMillis() + ".png";
File image= new File(imagesFolder, fname);
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
picturePath=image.getAbsolutePath();
bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bitmapOptions);
imageView.setImageBitmap(bitmap);
try this code
I am working on a application in which I have to click the image from the camera and save it into directory.I am able to create directory named MyPersonalFolder and also images are going into it but when I am trying to open that image to see, it doesn't open and shows the message that that image cannot be opened. here is my code. Can anyone please tell me what mistake I am doing here.
I have also mentioned permissions in manifest .
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
public class Camera extends Activity{
private static final String TAG = "Camera";
private static final int CAMERA_PIC_REQUEST = 1111;
Button click , share;
ImageView image;
String to_send;
String filename;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
image = (ImageView)findViewById(R.id.image);
share = (Button)findViewById(R.id.share);
click = (Button)findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BitmapDrawable bitmapDrawable = (BitmapDrawable)image.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
// Save this bitmap to a file.
File cache = getApplicationContext().getExternalCacheDir();
File sharefile = new File(cache, "toshare.png");
try {
FileOutputStream out = new FileOutputStream(sharefile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
}
// Now send it out to share
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + sharefile.getAbsolutePath()));
try {
startActivity(Intent.createChooser(share, "Share photo"));
} catch (Exception e) {
}
/*Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
//String to_send = null;
share.putExtra(Intent.EXTRA_TEXT, to_send);
startActivity(Intent.createChooser(share, "Share using..."));*/
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
FileOutputStream outStream = null;
if (requestCode == CAMERA_PIC_REQUEST) {
//2
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
image.setImageBitmap(thumbnail);
//3
share.setVisibility(0);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//4
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/MyPersonalFolder");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
//outStream.write(data[0]);
outStream.flush();
outStream.close();
//Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length + " to " + outFile.getAbsolutePath());
refreshGallery(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
/*try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
//5
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();*/
}
}
}
private void refreshGallery(File file) {
Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(file));
sendBroadcast(mediaScanIntent);
}
}
You will need to use MediaScanner to notify the system of the new file/directory. You can try something like this after creating and saving the new file:
/**
* Adds the new photo/video to the device gallery, else it will remain only visible via sd card
*
* #param path
*/
public static void addToGallery(Context context, String path) {
MediaScanner scanner = new MediaScanner(path, null);
MediaScannerConnection connection = new MediaScannerConnection(context, scanner);
scanner.connection = connection;
connection.connect();
}
/**
* Scans the sd card for new videos/images and adds them to the gallery
*/
private static final class MediaScanner implements MediaScannerConnection.MediaScannerConnectionClient {
private final String path;
private final String mimeType;
MediaScannerConnection connection;
public MediaScanner(String path, String mimeType) {
this.path = path;
this.mimeType = mimeType;
}
#Override
public void onMediaScannerConnected() {
connection.scanFile(path, mimeType);
}
#Override
public void onScanCompleted(String path, Uri uri) {
connection.disconnect();
}
}
EDIT:
You are also forgetting to write the byte array to the file specified in the output stream, like in the code that you have commented out. Try this at the end just before you refresh the gallery:
outStream = new FileOutputStream(outFile);
outStream.write(bytes.toByteArray()); //this is the line you had missing
outStream.flush();
outStream.close();
Also take note that using Intent.ACTION_MEDIA_SCANNER_SCAN_FILE to refresh the gallery can also present you with some security issues on kitkat (cant remember exactly what the issues were). So just make sure you test it on kitkat device to confirm that it works correctly
I my developing an app that clicks the photos and it should store the photos in a different folder than the default storage location. please guide me about it.
#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);
}
This is the basic code, please tell me the changes needed to make in it.
You cannot change default folder location, but you can make copy of image for your use. If you want to change it, then play with system camera.
You Need to call on activity result and get captured image and store it on any location.
For my case file(image) name is currenttimestamp.jpg
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK){
try {
AssetFileDescriptor videoAsset = getContentResolver().openAssetFileDescriptor(intent.getData(), "r");
FileInputStream fis = videoAsset.createInputStream();
File tmpFile = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis()+".jpg");
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
EDIT
tell android you have copied the picture. This will make the folder show up as a gallery on the users device just pass in the path and mimetype to a media scanner connection.
conn.scanFile(fos..getAbsolutePath(),"image/*");
**End edit *
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
*Edit setup the mediascanner connection *
private static MediaScannerConnection conn;
somewhere in onCreate()
conn = new MediaScannerConnection(this, this);
conn.connect();
#Override
public void onScanCompleted(String path, Uri uri) {
// now is good time to save stuff in the database because
// the last segment of the uri is the imageId in the mediaStore.
// you can easily pull a thumbnail from the mediaStore with the imageId.
// example of getting thumbnail
//final BitmapFactory.Options bmOptions = new BitmapFactory.Options();
// bmOptions.inSampleSize = 1;
//Bitmap bm = MediaStore.Images.Thumbnails.getThumbnail(
// context.getContentResolver(), newImageId,
// MediaStore.Images.Thumbnails.MINI_KIND,
// bmOptions);
}
#Override
public void onMediaScannerConnected() {
//toast ready
// enable your camera button
}
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyProjectName");
if (!imagesFolder.exists()) {
imagesFolder.mkdirs();// <----Do Not Forget this
}
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy_HHmmss_Z");
String currentDateandTime = sdf.format(new Date());
String fileName = "image_" + String.valueOf(currentDateandTime) + ".jpg";
File output = new File(imagesFolder, fileName);
Uri uriSavedImage = Uri.fromFile(image);
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();
}
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
I'm working on a project, that read image file from drawable folder through ImageView, it loaded successfully through
ImageView view = (ImageView) findViewById(R.id.imageView);
view.setOnTouchListener(this);
buttonTakePicture = (Button) findViewById(R.id.takepicture);
buttonTakePicture.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback, myPictureCallback_RAW,
myPictureCallback_JPG);
now after pressing takePicture button , image should save in sdcard, it is taking snapshot but not saving the image with that, the code is below
File file = new File(mScreenshotPath + "/" + System.currentTimeMillis() + ".jpg");
FileOutputStream fos;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
Toast.makeText(AndroidCamera.this,
"Image saved: " + uriTarget.toString(),
Toast.LENGTH_LONG).show();
Please help me for this issue....Thanks in advance
You can save photos in Android without the need for an OutputStream and all the other logic that accompanies it. Here is a simple recipe which will do what I think you are trying to accomplish. Pay special attention to the Intent and how it is used to set up the saving of the image, as this is I think where you are going wrong.
public class PhotoActivity extends Activity implements OnClickListener {
private Button takePicture;
private String path;
private File imageFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
takePicture = (Button) findViewById(R.id.button1);
takePicture.setOnClickListener(this);
path = Environment.getExternalStorageDirectory() + "/my_image.png";
imageFile = new File(path);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri uri = Uri.fromFile(imageFile);
i.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivity(i);
break;
}
}
}
private static final int CAMERA_REQUEST = 1888;
buttonTakePicture.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, getImageUri());
startActivityForResult(intent, CAMERA_REQUEST);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST) {
photo = (Bitmap) data.getExtras().get("data");
}
}
private Uri getImageUri() {
File file1 = new File(Environment.getExternalStorageDirectory() + "/Camerafolder");
if (!file1.exists())
{
file1.mkdirs();
}
File file = new File(Environment.getExternalStorageDirectory() + "/Camerafolder/"+"img"+".png");
Uri imgUri = Uri.fromFile(file);
return imgUri;
}