28

On a certain tap event, I ask the user to add an image. So I provide two options:

  1. To add from gallery.
  2. To click a new image from camera.

My aim is to keep a list of "uri"s related to those images.

If the user chooses gallery, then I get the image uri (which is quite simple). But if he chooses camera, then after taking a picture, I am getting the Bitmap object of that picture.

Now how do I convert that Bitmap object to uri, or in other words, how can I get the relative Uri object of that bitmap object?

Thanks.

Ron
  • 24,175
  • 8
  • 56
  • 97
Darshan Bidkar
  • 515
  • 2
  • 6
  • 9
  • This might help http://stackoverflow.com/questions/7636697/get-path-and-filename-from-camera-intent-result – Vishal Vyas Sep 23 '12 at 20:00
  • some of the code is pretty much hardcoded. I don't want to hard code the file name of the image. And not necessarily the image is saved in the DCIM folder.. – Darshan Bidkar Sep 24 '12 at 06:32

6 Answers6

58

I have same problem in my project, so i follow the simple method (click here) to get Uri from bitmap.

public Uri getImageUri(Context inContext, Bitmap inImage) {
  ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
  String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
  return Uri.parse(path);
} 
blueware
  • 5,205
  • 1
  • 40
  • 60
Ajay
  • 4,850
  • 2
  • 32
  • 44
7
Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);

the line mentioned above create a thumbnail using bitmap, that may consume some extra space in your android device.

This method may help you to get the Uri from bitmap without consuming some extra memory.

public Uri bitmapToUriConverter(Bitmap mBitmap) {
   Uri uri = null;
   try {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, 100, 100);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    Bitmap newBitmap = Bitmap.createScaledBitmap(mBitmap, 200, 200,
            true);
    File file = new File(getActivity().getFilesDir(), "Image"
            + new Random().nextInt() + ".jpeg");
    FileOutputStream out = getActivity().openFileOutput(file.getName(),
            Context.MODE_WORLD_READABLE);
    newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
    out.flush();
    out.close();
    //get absolute path
    String realPath = file.getAbsolutePath();
    File f = new File(realPath);
    uri = Uri.fromFile(f);

  } catch (Exception e) {
    Log.e("Your Error Message", e.getMessage());
  }
return uri;
}


public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) >= reqHeight
                && (halfWidth / inSampleSize) >= reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

for more details goto Loading Large Bitmaps Efficiently

Harikesh
  • 311
  • 4
  • 6
Hanan
  • 444
  • 4
  • 16
  • what is calculateInSampleSize ?? Please add method for it – Anand Savjani Aug 13 '16 at 03:55
  • @Anand : This http://stackoverflow.com/questions/2641726/decoding-bitmaps-in-android-with-the-right-size may help you, if you find proper solution then please inform. – Hanan Aug 23 '16 at 15:27
  • you can ignore inSampleSize. Setting samplesize to 2 will reduce image quality by 2, as if taking only each second pixel of the image, something like that. Putting 1 or not setting this option would be ok. – lxknvlk Dec 21 '16 at 17:28
  • 1
    i can confirm what i said about inSampleSize. Also, this method would distort image if it is not rectangular. To work with images other than rectangular, use this line `Bitmap newBitmap = Bitmap.createScaledBitmap(mBitmap, mBitmap.getWidth(), mBitmap.getHeight(), true);` – lxknvlk Dec 21 '16 at 17:51
  • This always returns null for me. – Marc Alexander Sep 13 '18 at 16:47
  • according to [this doc](https://developer.android.com/reference/android/content/Context#MODE_WORLD_READABLE) . creating files with `Context.MODE_WORLD_READABLE `is a security risk as it allows files to be read by other applications. Using it on Android N and above throws `SecurityException` – danijax Mar 25 '20 at 08:17
  • @danijax So what is your solution? – Sadegh J Jun 12 '21 at 13:26
  • Where do you set options to bitmap?? – Sadegh J Jun 12 '21 at 13:41
1

This is what worked for me. For example getting thumbnail from a video in the form of a bitmap. Then we can convert the bitmap object to uri object.

String videoPath = mVideoUri.getEncodedPath();
System.out.println(videoPath); //prints to console the path of the saved video
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Images.Thumbnails.MINI_KIND);

 Uri thumbUri = getImageUri(this, thumb);
Ronny K
  • 3,641
  • 4
  • 33
  • 43
0

I tried the following code snippet from the post I mentioned in my comment.. and it's working fine for me.

/**
 * Gets the last image id from the media store
 * 
 * @return
 */
private int getLastImageId() {
    final String[] imageColumns = { MediaStore.Images.Media._ID,
            MediaStore.Images.Media.DATA };
    final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
    Cursor imageCursor = managedQuery(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns,
            null, null, imageOrderBy);
    if (imageCursor.moveToFirst()) {
        int id = imageCursor.getInt(imageCursor
                .getColumnIndex(MediaStore.Images.Media._ID));
        String fullPath = imageCursor.getString(imageCursor
                .getColumnIndex(MediaStore.Images.Media.DATA));
        Log.d(getClass().getSimpleName(), "getLastImageId::id " + id);
        Log.d(getClass().getSimpleName(), "getLastImageId::path "
                + fullPath);
        imageCursor.close();
        return id;
    } else {
        return 0;
    }
}

OutPut in logcat:

09-24 16:36:24.500: getLastImageId::id 70
09-24 16:36:24.500: getLastImageId::path /mnt/sdcard/DCIM/Camera/2012-09-24 16.36.20.jpg

Also I don't see any harcoded names in the above code snippet. Hope this helps.

Community
  • 1
  • 1
Vishal Vyas
  • 2,571
  • 1
  • 22
  • 39
0

Try to use the below Code. May be helpful to you:

new AsyncTask<Void, Integer, Void>() {
            protected void onPreExecute() {
            };

            @Override
            protected Void doInBackground(Void... arg0) {
                imageAdapter.images.clear();
                initializeVideoAndImage();
                return null;
            }

            protected void onProgressUpdate(Integer... integers) {
                imageAdapter.notifyDataSetChanged();
            }

            public void initializeVideoAndImage() {
                final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Thumbnails._ID };
                String orderBy = MediaStore.Images.Media._ID;
                Cursor imageCursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);

                final String[] videocolumns = { MediaStore.Video.Thumbnails._ID, MediaStore.Video.Media.DATA };
                orderBy = MediaStore.Video.Media._ID;
                Cursor videoCursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videocolumns, null, null, orderBy);
                int i = 0;
                int image_column_index = 0;

                if (imageCursor != null) {
                    image_column_index = imageCursor.getColumnIndex(MediaStore.Images.Media._ID);
                    int count = imageCursor.getCount();
                    for (i = 0; i < count; i++) {
                        imageCursor.moveToPosition(i);
                        int id = imageCursor.getInt(image_column_index);
                        ImageItem imageItem = new ImageItem();
                        imageItem.id = id;
                        imageAdapter.images.add(imageItem);

                    }
                }

                if (videoCursor != null) {
                    image_column_index = videoCursor.getColumnIndex(MediaStore.Video.Media._ID);
                    int count = videoCursor.getCount();
                    for (i = 0; i < count; i++) {
                        videoCursor.moveToPosition(i);
                        int id = videoCursor.getInt(image_column_index);
                        ImageItem imageItem = new ImageItem();
                        imageItem.id = id;
                        imageAdapter.images.add(imageItem);
                    }
                }
                publishProgress(i);
                if (imageCursor != null) {
                    image_column_index = imageCursor.getColumnIndex(MediaStore.Images.Media._ID);
                    int count = imageCursor.getCount();
                    for (i = 0; i < count; i++) {
                        imageCursor.moveToPosition(i);
                        int id = imageCursor.getInt(image_column_index);
                        int dataColumnIndex = imageCursor.getColumnIndex(MediaStore.Images.Media.DATA);
                        ImageItem imageItem = imageAdapter.images.get(i);
                        Bitmap img = MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), id, MediaStore.Images.Thumbnails.MICRO_KIND, null);
                        int column_index = imageCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        imageItem.imagePath = imageCursor.getString(column_index);
                        imageItem.videoPath = "";
                        try {
                            File imageFile = new File(Environment.getExternalStorageDirectory(), "image" + i);
                            imageFile.createNewFile();
                            ByteArrayOutputStream bos = new ByteArrayOutputStream();

                            if (bos != null && img != null) {
                                img.compress(Bitmap.CompressFormat.PNG, 100, bos);
                            }
                            byte[] bitmapData = bos.toByteArray();
                            FileOutputStream fos = new FileOutputStream(imageFile);
                            fos.write(bitmapData);
                            fos.close();
                            imageItem.thumbNailPath = imageFile.getAbsolutePath();
                            try {
                                boolean cancelled = isCancelled();
                                // if async task is not cancelled, update the
                                // progress
                                if (!cancelled) {
                                    publishProgress(i);
                                    SystemClock.sleep(100);

                                }

                            } catch (Exception e) {
                                Log.e("Error", e.toString());
                            }
                            // publishProgress();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        // imageAdapter.images.add(imageItem);
                    }
                }
                imageCursor.close();

                if (videoCursor != null) {
                    image_column_index = videoCursor.getColumnIndex(MediaStore.Video.Media._ID);
                    int count = videoCursor.getCount() + i;
                    for (int j = 0; i < count; i++, j++) {
                        videoCursor.moveToPosition(j);
                        int id = videoCursor.getInt(image_column_index);
                        int column_index = videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
                        ImageItem imageItem = imageAdapter.images.get(i);
                        imageItem.imagePath = videoCursor.getString(column_index);
                        imageItem.videoPath = imageItem.imagePath;
                        System.out.println("External : " + imageItem.videoPath);
                        try {
                            File imageFile = new File(Environment.getExternalStorageDirectory(), "imageV" + i);
                            imageFile.createNewFile();
                            ByteArrayOutputStream bos = new ByteArrayOutputStream();
                            MediaMetadataRetriever mediaVideo = new MediaMetadataRetriever();
                            mediaVideo.setDataSource(imageItem.videoPath);
                            Bitmap videoFiles = mediaVideo.getFrameAtTime();
                            videoFiles = ThumbnailUtils.extractThumbnail(videoFiles, 96, 96);
                            if (bos != null && videoFiles != null) {
                                videoFiles.compress(Bitmap.CompressFormat.JPEG, 100, bos);

                            }
                            byte[] bitmapData = bos.toByteArray();
                            FileOutputStream fos = new FileOutputStream(imageFile);
                            fos.write(bitmapData);
                            fos.close();
                            imageItem.imagePath = imageFile.getAbsolutePath();
                            imageItem.thumbNailPath = imageFile.getAbsolutePath();
                            try {
                                boolean cancelled = isCancelled();
                                // if async task is not cancelled, update the
                                // progress
                                if (!cancelled) {
                                    publishProgress(i);
                                    SystemClock.sleep(100);

                                }

                            } catch (Exception e) {
                                Log.e("Error", e.toString());
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                }
                videoCursor.close();
            }

            protected void onPostExecute(Void result) {
                imageAdapter.notifyDataSetChanged();
            };

        }.execute();

    }
Parth Patel
  • 859
  • 2
  • 11
  • 28
Jay Thakkar
  • 743
  • 1
  • 5
  • 24
0

Note : if you are using android 6.0 or greater version path will give null value. so you have to add permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

public void onClicked(View view){
        Bitmap bitmap=getBitmapFromView(scrollView,scrollView.getChildAt(0).getHeight(),scrollView.getChildAt(0).getWidth());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG,90,baos);
        String path = MediaStore.Images.Media.insertImage(getContentResolver(),bitmap,"title",null);
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/jpeg");
        intent.putExtra(Intent.EXTRA_STREAM,Uri.parse(path));
        startActivity(Intent.createChooser(intent,"Share Screenshot Using"));
    }
blueware
  • 5,205
  • 1
  • 40
  • 60
Omi
  • 1
  • 2