Image is does not show in ImageView dynamically from sdcard - android

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

Related

Get last captured image?

I have an application, where you can take a picture about yourself (the app saves the image in a specified folder called "MyAppImage"), and I want to display the taken image in a second activity with a code, how to do this? I want to display it in a imageView in my SecondActivity, but I need a code that can get the last captured camera image from this folder, is there any way to do this?
Hope someone can guide me, how to do this, thanks!
After take photo:
MainActivity
String filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
String fileName = "yourPhotoName" + ".jpg"
filePath = "pathOfMyAppImageFolder" + fileName;
File destination = new File(filePath);
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), AnotherActivity.class);
intent.putExtra("filePath", filePath)
startActivity(intent);
}
});
AnotherActivity
String filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
filePath = intent.getStringExtra("filePath");
File imgFile = new File(filePath);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
}
Take the last photo of the folder:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<File> files = getListFiles(new File("MyAppImageFolderPath"));
File imgFile = files.get(files.size());
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
}
private List<File> getListFiles(File parentDir) {
ArrayList<File> inFiles = new ArrayList<File>();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
if(file.getName().endsWith(".jpg")){ //change to your image extension
inFiles.add(file);
}
}
}
return inFiles;
}
Once you takePhoto, save it into file.
Then call intent to start second activity and putExtraString with your image file path.
That is all.

Android - Take a picture from the Camera and save it to the internal storage

I have been stuck on this problem for a while now.
I am trying to take a picture with the Camera and save the full size picture directly into the internal memory.
I can save to the external storage without a glitch, but for some reason I cannot get it to work for the internal memory.
The solution below ONLY saves the small picture returned by the data object, and not the full-size picture.
It seems that the camera does not retrieve the full size picture, or that when I use file functions (new File, FileOutputStream...), Android is not retrieving the image from the camera Intent (shows a blank image).
I read all the forums, tutorials and tried different ways of achieving this, but I have not found the answer. I can't be the only one trying to do this.
Could you please help me with this problem?
Thanks!
Here is my code:
public class AddItem extends Fragment {
ListCell cell = new ListCell();
View view;
private Bitmap mImageBitmap;
protected myCamera cameraObject = null;
private Button saveBtn;
private Button cancelBtn;
DBSchema dbSchema;
protected boolean bdisplaymessage;
protected boolean ExternalStorage = false;
public AddItem(){
}
private class ListCell{
private EditText total;
private ImageView mImageView;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.add_item, container,
false);
saveBtn = (Button) rootView.findViewById(R.id.SaveItem);
cancelBtn = (Button) rootView.findViewById(R.id.CancelItem);
cameraObject = new myCamera();
cell.total = (EditText) rootView.findViewById(R.id.item_total_Value);
cell.mImageView = (ImageView) rootView.findViewById(R.id.item_logo);
cell.mImageView.setImageResource(R.drawable.camera_icon);
cell.mImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
saveBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//save item to internal db
//get names of columns from db
bdisplaymessage = true;
dbSchema = new DBSchema();
Transaction transac = dbSchema.new Transaction();
Context context = getActivity().getApplicationContext();
//put values in content values
ContentValues values = new ContentValues();
values.put(transac.Total,cell.total.getText().toString());
StatusData statusData = ((MyFunctions) getActivity().getApplication()).statusData;
long nInsert = 0;
nInsert = statusData.insert(values,dbSchema.table_transaction);
if(nInsert!=0){
Toast.makeText(context, "inserted " + nInsert , Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(context, "not inserted " + nInsert , Toast.LENGTH_LONG).show();
}
}
});
cancelBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//redirect to home page
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new LoadMenu()).commit();
}
});
return rootView;
}
// Some lifecycle callbacks so that the image can survive orientation change
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelable(cameraObject.BITMAP_STORAGE_KEY, mImageBitmap);
outState.putBoolean(cameraObject.IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
super.onSaveInstanceState(outState);
}
//take picture
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//takePictureIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String mCurrentPhotoPath;
File f = null;
try {
//create image
f = cameraObject.setUpPhotoFile(getResources().getString(R.string.album_name),ExternalStorage, getActivity().getApplicationContext());
cameraObject.setCurrentPath(f.getAbsolutePath());
Log.d("uri_fromfile",Uri.fromFile(f).toString());
//uncomment the line below when ExternalStorage=true
//takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
startActivityForResult(takePictureIntent, cameraObject.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestcode, int resultCode, Intent data) {
if (requestcode == cameraObject.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == getActivity().RESULT_OK) {
handleCameraPhoto(data);
}
}
private void handleCameraPhoto(Intent data) {
setPic(data);
galleryAddPic();
}
private void setPic(Intent data) {
/* There isn't enough memory to open up more than a couple camera photos */
/* So pre-scale the target bitmap into which the file is decoded */
/* Get the size of the ImageView */
int targetW = cell.mImageView.getWidth();
int targetH = cell.mImageView.getHeight();
/* Get the size of the image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(cameraObject.getCurrentPath(), bmOptions);
Log.d("image_path",cameraObject.getCurrentPath());
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
/* Figure out which way needs to be reduced less */
int scaleFactor = 1;
if ((targetW > 0) || (targetH > 0)) {
scaleFactor = Math.min(photoW/targetW, photoH/targetH);
}
/* Set bitmap options to scale the image decode target */
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
/* Decode the JPEG file into a Bitmap */
Bitmap bitmap = null;
if(ExternalStorage){
bitmap = BitmapFactory.decodeFile(cameraObject.getCurrentPath(), bmOptions);
}
else{
File internalStorage = getActivity().getApplicationContext().getDir("imageDir", Context.MODE_PRIVATE);
File reportFilePath = new File(internalStorage, cameraObject.JPEG_FILE_PREFIX +"hello" + ".jpg");
String picturePath = reportFilePath.toString();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(reportFilePath);
bitmap = (Bitmap) data.getExtras().get("data");
bitmap.compress(Bitmap.CompressFormat.PNG, 100 /*quality*/, fos);
fos.close();
}
catch (Exception ex) {
Log.i("DATABASE", "Problem updating picture", ex);
picturePath = "";
}
/* below is a bunch of options that I tried with decodefile, FileOutputStream... none seems to work */
//File out = new File(getActivity().getApplicationContext().getFilesDir(),cameraObject.JPEG_FILE_PREFIX + "hello");
//bitmap = BitmapFactory.decodeFile(out.getAbsolutePath());
//FileOutputStream fos = null;
//try {
//fos = new FileOutputStream(new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX).getAbsolutePath());
//bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
// Use the compress method on the BitMap object to write image to the OutputStream
//fos.close();
//Bitmap bitmap = null;
/*try{
FileInputStream fis = new FileInputStream(new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX).getAbsolutePath());
//getActivity().getApplicationContext().openFileInput(cameraObject.getCurrentPath());
bitmap = BitmapFactory.decodeStream(fis);
//
fis.close();
}
catch(Exception e){
Log.d("what?",e.getMessage());
bitmap = null;
}*/
/*} catch (Exception e) {
e.printStackTrace();
}*/
/*File mypath=new File(getActivity().getApplicationContext().getFilesDir(),"/" + cameraObject.JPEG_FILE_PREFIX + "hello" + cameraObject.JPEG_FILE_SUFFIX);
bitmap = BitmapFactory.decodeFile(mypath.getAbsolutePath());*/
//bitmap = (Bitmap) data.getExtras().get("data");
}
/* Associate the Bitmap to the ImageView */
cell.mImageView.setImageBitmap(bitmap);
cell.mImageView.setVisibility(View.VISIBLE);
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(cameraObject.mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
}
My other class called myCamera handles the camera:
public class myCamera extends MainMenu{
private ImageView mImageView;
private Bitmap mImageBitmap;
static final String BITMAP_STORAGE_KEY = "viewbitmap";
static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
protected static final int ACTION_TAKE_PHOTO_B = 1;
protected static final int ACTION_TAKE_PHOTO_S = 2;
protected int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = MEDIA_TYPE_IMAGE;
protected Uri fileUri;
protected String mCurrentPhotoPath;
protected static final String JPEG_FILE_PREFIX = "IMG_";
protected static final String JPEG_FILE_SUFFIX = ".jpg";
private static final String CAMERA_DIR = "/dcim/";
protected String mAlbumName;
protected AlbumStorageDirFactory mAlbumStorageDirFactory = null;
protected String getAlbumName() {
return "test";
}
protected String getCurrentPath(){
return mCurrentPhotoPath;
}
protected void setCurrentPath(String mCurrentPhotoPath){
this.mCurrentPhotoPath=mCurrentPhotoPath;
}
public File getAlbumStorageDir(String albumName) {
return new File (
Environment.getExternalStorageDirectory()
+ CAMERA_DIR
+ albumName
);
}
private File getAlbumDir() {
File storageDir = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
} else {
mAlbumStorageDirFactory = new BaseAlbumDirFactory();
}
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = getAlbumStorageDir(getAlbumName());
if (storageDir != null) {
if (! storageDir.mkdirs()) {
if (! storageDir.exists()){
Log.d("CameraSample", "failed to create directory");
return null;
}
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.base_for_drawer);
mAlbumName = getIntent().getStringExtra("AlbumName");
}
public myCamera(){
}
//save full size picture
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File storageDir = getAlbumDir();
File image = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, storageDir);
return image;
}
protected File setUpPhotoFile(String albumName, boolean ExternalStorage, Context context) throws IOException {
mAlbumName = albumName;
File f =null;
if(ExternalStorage){
f = createImageFile();
}
else{
f = saveToInternalSorage(context);
}
// Save a file: path for use with ACTION_VIEW intents
if(f !=null){
mCurrentPhotoPath = f.getAbsolutePath();
}
return f;
}
private File saveToInternalSorage(Context context) throws IOException{
ContextWrapper cw = new ContextWrapper(context);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + "hello";
// path to /data/data/yourapp/app_data/imageDir
File directory = context.getDir("imageDir", Context.MODE_PRIVATE);
File mypath=new File(directory,imageFileName + JPEG_FILE_SUFFIX);
/*below is a bunch of options that I tried*/
//File directory =context.getFilesDir();
//File directory = new File(getFilesDir(),imageFileName,Context.MODE_PRIVATE);
// Create imageDir
//File image = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, storageDir);
//File mypath = File.createTempFile(imageFileName,JPEG_FILE_SUFFIX, directory);
//return image;
return mypath;
}
}
I found the solution! I did not use the native camera application, but rather created my own camera class and use the data sent back by the camera via a callback. Works smoothly!

How to set Image on ImageButton dynamically?

I want to set an image on a button in my app, dynamically from a file on the sdcard. I have tried this code but it is not working. I have tried to convert the image to a bitmap object and I set that object to ImageButton, but it isn't showing anything. How can I solve this issue?
My code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File imageFile = new File("/sdcard0/DCIM/camera/jbn.jpg");
Bitmap bmp = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ImageButton button1 = (ImageButton)findViewById(R.id.imgBtn);
button1.setImageBitmap(bmp);
}
XML
<ImageButton
android:layout_width="200dip"
android:layout_height="200dip"
android:id="#+id/imgBtn"
/>
Algorithm
void loadPic()
{
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String pathName = baseDir + "/DCIM/camera/";
File parentDir=new File(pathName);
File[] files = parentDir.listFiles();
Date lastDate;
String lastFileName;
boolean isFirstFile = true; //just temp variable for being sure that we are on the first file
for (File file : files) {
if(isFirstFile){
lastDate = new Date(file.lastModified());
isFirstFile = false;
}
if(file.getName().endsWith(".jpg") || file.getName().endsWith(".jpeg")){
Date lastModDate = new Date(file.lastModified());
if (lastModDate.after(lastDate)) {
lastDate = lastModDate;
lastFileName = file.getName();
}
}
}
Try with something simple like this for example:
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "jbn.jpg";
String pathName = baseDir + "/your/folder(s)/" +_ fileName; //maybe your folders are /DCIM/camera/
Bitmap bmp = BitmapFactory.decodeFile(pathName);
ImageButton button1 = (ImageButton)findViewById(R.id.imgBtn);
button1.setImageBitmap(bmp);
Try to get get AbsolutePath of image file :
File imageFile = new File("/sdcard0/DCIM/camera/jibin.jpg");
Bitmap bmp = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
You can try something like this -
String path = Environment.getExternalStorageDirectory()
+ "/Images/test.jpg";
File imgFile = new File(path);
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
.getAbsolutePath());
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(myBitmap);
}
If you want to set the image dynamically from any URL that you have, set the image in this way. You can also set the bitmap width and height.
private class LoadImage extends AsyncTask<Bundle, String, Bitmap> {
Bitmap bitmap;
#Override
protected Bitmap doInBackground(Bundle... args) {
extras=args[0];
try {
InputStream in = new java.net.URL("Enter your URL").openStream();
bitmap = BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
imageButton.setImageBitmap(image);
}
}
And if you want to set the image from the local directory or from the resources folder then just fetch the Image from the folder and set that in image and you don't need to convert it into a Bitmap.
Thanks

How to save images from imageView to SD

I save a picture from imageView to SD. The image is saved.
The problem is that there is the first image, and saving the next image again saved the first with a different name.
As I understand need to catch the moment when the picture from imageView is loaded into playImage. But how to do it?
Thank's.
Load the image in imageView and save to sd:
public class Gallery extends Activity implements OnClickListener {
String item;
Button btnsave, btnhome;
ImageView playImage;
String fotoname;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gallery);
btnhome = (Button) findViewById(R.id.btn_home);
btnhome.setOnClickListener(this);
btnsave = (Button)findViewById(R.id.btn_save);
btnsave.setOnClickListener(this);
playImage = (ImageView)findViewById(R.id.displayImage);
final ImageView playImage = (ImageView) findViewById(R.id.displayImage);
final LinearLayout myGallery = (LinearLayout) findViewById(R.id.mygallery1);
Bundle extras = getIntent().getExtras();
if(extras !=null) {
item = extras.getString("item");
if(item.equals("Item")){
try {
String galleryDirectoryName = "ITEM/item";
String[] listImages = getAssets().list(galleryDirectoryName);
for (String imageName : listImages) {
InputStream is = getAssets().open(galleryDirectoryName + "/" + imageName);
final Bitmap bitmap = BitmapFactory.decodeStream(is);
ImageView imageView = new ImageView(getApplicationContext());
imageView.setLayoutParams(new ViewGroup.LayoutParams(350, 225));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(bitmap);
imageView.setPadding(10, 70, 10, 70);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
playImage.setImageBitmap(bitmap);
playImage.setPadding(5, 0, 5, 0);
}
});
myGallery.addView(imageView);
}
} catch (IOException e) {
Log.e("GalleryWithHorizontalScrollView", e.getMessage(), e);
}
}
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.btn_save:
playImage.setDrawingCacheEnabled(true);
Bitmap bitmap = playImage.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/." + (getString(R.string.app_name)));
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "photo-"+ n +".jpg";
File file = new File (newDir, fotoname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
Toast.makeText(this, (getString(R.string.saved)), Toast.LENGTH_SHORT ).show();
} catch (Exception e) {
}
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(newDir, fotoname);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
break;
case R.id.btn_home:
finish();
}
}
}
Check this.
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ll.setDrawingCacheEnabled(true);
Bitmap bitmap = ll.getDrawingCache();
// bitmap = Bitmap.createBitmap(480, 800,
// Bitmap.Config.ARGB_8888);
String root = Environment.getExternalStorageDirectory()
.toString();
File newDir = new File(root + "/Collage_Maker");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "cm_"+n + ".jpg";
File file = new File(newDir, fotoname);
String s = file.getAbsolutePath();
Log.i("Path of saved image.", s);
System.err.print("Path of saved image." + s);
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
Toast.makeText(getApplicationContext(), "Photo Saved "+ fotoname,
Toast.LENGTH_SHORT).show();
out.close();
} catch (Exception e) {
Log.e("Exception", e.toString());
}
}
});

Android Carry Camera Image To New Activity

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);

Categories

Resources