Jay
Jay

Reputation: 5084

Android Image not getting stored in Storage

I'm trying to store a newly captured image through the Camera on my Storage and then display the image on an imageview. However, the image does not get stored.

My code:

private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;

......more code...

captureImage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mCamera.takePicture(null, null, new PictureCallback() {
                    @Override
                    public void onPictureTaken(byte[] data, Camera camera) {

                        File pictureFile;
                        pictureFile = new File(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));


                        try {
                            FileOutputStream fos = new FileOutputStream(pictureFile);
                            fos.write(data);
                            fos.close();
                        }
                        catch (Exception e) {
                            Log.d("ERR",e.toString());
                        }

                        //Display
                        Uri uri = Uri.fromFile(pictureFile);
                        imageViewer.setImageURI(uri);

                     }
                });
            }
        });

Is my code correct for writing and displaying the image? I do not see any image on my storage and the imageview doesn't get populated by the image either. What am I doing wrong?

Upvotes: 0

Views: 124

Answers (3)

user5292387
user5292387

Reputation: 413

First, does your app's manifest contain the necessary permission to write to the SD card?

<manifest ...>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    ...
</manifest>

and second, I'm not sure that you have the correct path to the SD card. The API docs suggest:

File sdPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String filename = Long.toString(System.currentTimeMillis())+".jpg";
File pictureFile;
pictureFile = new File(sdPath, filename);

EDIT: To display the image using the URL, you could try:

FileInputStream inputStream = new FileInputStream(pictureFile);  
Drawable d = Drawable.createFromStream(inputStream, pictureFile.getName());
imageViewer.setImageDrawable(d);

Upvotes: 0

Erik Jhordan Rey
Erik Jhordan Rey

Reputation: 748

1- make sure you have what it takes Permissions

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

2- Create a directory on your mobile

 public static void createDirectory(Context context) {

      String directoryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/YOURDIRECTORYNAME";
            try {
                File directory = new File(directoryPath);
                if (!directory.exists()) {
                    directory.mkdirs();
                }
            } catch (Exception e) {
                  e.printStackTrace();
            }


        }

3- This method used to take the photo and create file.

private void takePictures() {

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {

            File photoFile = null;

            try {
                photoFile = createImageFile();
            } catch (IOException ex) {

            }

            if (photoFile != null) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }

        }

    }

4- Creates the file and save it in the folder.

     private File createImageFile() throws IOException {
            Calendar c = Calendar.getInstance();
            SimpleDateFormat timeData = new SimpleDateFormat("dd-MMM-yyyy-HH:mm:ss");
//TODO declared global variables datePicture and imageFileName 
            datePicture = timeData.format(c.getTime());
            imageFileName = Config.IMAGE_NAME_DEFOULT + datePicture;
            File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/YOURDIRECTORYNAME");
            File image = File.createTempFile(imageFileName, ".png", storageDir);
           Log.v("test_photo" ,image.getName());
//TODO declared global variables fileName and mCurrentPhotoPath
            fileName = image.getName();
            mCurrentPhotoPath = image.getAbsolutePath();
           return image;
        }

5- Get the picture reveal it in your imageView and save in your DB.

      @Override
            public void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);

                if (requestCode == REQUEST_IMAGE_CAPTURE) {
                    if (resultCode == getActivity().RESULT_OK) {


//show directly 

Bundle extras = data.getExtras();
Bitmap bitmap = extras.get("data");
youtImageView.setImageBitmap(bitmap);

                  /* here show in your imageView directly or
             insert into database variables fileName and mCurrentPhotoPath 
    then you'll have to get it if you want to display from the DB */

                    } else if (resultCode == getActivity().RESULT_CANCELED) {

                    } 
                }


            }

I hope it helps!

Upvotes: 0

Harshikesh Kumar
Harshikesh Kumar

Reputation: 374

Create folder where you want to keep your photos. Give full path name to create file .

//in this example MyImages is folder where you will keep your photos

 File storageDir = new File(Environment.getExternalStorageDirectory() + "/", "MyImages");

            if (!storageDir.exists()) {
                storageDir.mkdirs();//directory created
            }
            // get the current timestamp
            String timest = new SimpleDateFormat("yyyyMMdd_HHmmss")
                    .format(new Date());
//Create your picture file
 File pictureFile;
 pictureFile = new File(storageDir.getPath()+File.separator+ "IMG_" + timeStamp + ".jpg");

Upvotes: 1

Related Questions