2

I have a function::

    public void onPictureTaken(byte[] data, Camera camera) {

    //Creating the Image file here
    }



 public static void addImageToGallery(final String filePath, final Context context) {

        ContentValues values = new ContentValues();

        values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.MediaColumns.DATA, filePath);

        context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    }

  1. How to create a file from data properly.
  2. I want to create a file and get the absolute path of the file
  3. Finally I want to add the image into the gallery, for which I already have the function
4
  • see MediaStore.Images.Media#insertImage() Commented Aug 26, 2017 at 5:07
  • did you see its javadocs: "Insert an image and create a thumbnail for it. Returns The URL to the newly created image, or null if the image failed to be stored for any reason." ? Commented Aug 26, 2017 at 5:14
  • How to create thumbnail ? Commented Aug 26, 2017 at 5:28
  • 1
    use MediaStore.Images.Media#insertImage() Commented Aug 26, 2017 at 5:29

2 Answers 2

3

Try something like this..

private void createFile(byte[] fileData) {
            try {
                //Create directory..
                File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/YOUR_FOLDER_NAME");
                File dir = new File(root + File.separator);
                if (!dir.exists()) dir.mkdir();

                //Create file..
                File file = new File(root + File.separator + "YOUR_IMAGE_NAME");
                file.createNewFile();

                FileOutputStream out = new FileOutputStream(file);
                out.write(fileData);
                out.close();

            }
            catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
Sign up to request clarification or add additional context in comments.

Comments

2

Creating file from byte array:

FileOutputStream fos = new FileOutputStream("pathname");
fos.write(myByteArray);
fos.close();

or use Apache Commons IO (home):

FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.