48

I'm trying to share images with Facebook, twitter, etc using SHARE INTENT from Android.

I found code to send a image to the share intent, but this code needs the URI of the bitmap: fullSizeImageUri

This is the full code:

private void startShareMediaActivity(Bitmap image) {
    boolean isVideo=false;
    String mimeType="bmp";
    Uri fullSizeImageUri=null;
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setType(mimeType);
    intent.putExtra(Intent.EXTRA_STREAM, fullSizeImageUri);
    try {
        startActivity(Intent.createChooser(intent, (isVideo ? "video" : "image")));
    } catch (android.content.ActivityNotFoundException ex) { }
}

How to transform a Bitmap into a Uri?

8 Answers 8

96

Here is the Colin's Blog who suggest the simple method to convert bitmap to Uri Click here

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);
}
9
  • 16
    Note this creates an image that will stick around in the users gallery.
    – ocross
    Commented Mar 11, 2016 at 17:35
  • 6
    path can be null, if so, Uri.parse(path) will make app crash Commented Aug 5, 2017 at 22:18
  • 3
    Dont forget to take WRITE_EXTERNAL_STORAGE permission. Otherwise insertImage method may return null. See : stackoverflow.com/a/35283353/3341089
    – oguzhan
    Commented Sep 27, 2017 at 7:47
  • 2
    Not workking in android oreo, String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null); path will get null. Commented Oct 30, 2017 at 13:31
  • 1
    This method is deprecated Commented Feb 17, 2021 at 14:49
23
String FILENAME = "image.png";
String PATH = "/mnt/sdcard/"+ FILENAME;
File f = new File(PATH);
Uri yourUri = Uri.fromFile(f);
5
  • 2
    Parse always take as argument a String not a file. Next time read details about functions or maybe test them. Commented Nov 29, 2011 at 8:25
  • 14
    can't we get Uri without saving the bitmap
    – Prasad
    Commented Nov 19, 2014 at 9:34
  • work in android studio 2022 bumblebee Commented Aug 13, 2022 at 8:29
  • @rezarahmad Dear sheldon, This was answered 10 years back, Commented Jul 28, 2023 at 12:39
  • @KK_07k11A0585 yes this still working until 2023 and more future years Commented Jul 29, 2023 at 1:56
6

The latest solution I found is this. Its in kotlin you can covert it in Java.

    // Get uri of images from camera function
private fun getImageUri(inContext: Context?, inImage: Bitmap): Uri {

    val tempFile = File.createTempFile("temprentpk", ".png")
    val bytes = ByteArrayOutputStream()
    inImage.compress(Bitmap.CompressFormat.PNG, 100, bytes)
    val bitmapData = bytes.toByteArray()

    val fileOutPut = FileOutputStream(tempFile)
    fileOutPut.write(bitmapData)
    fileOutPut.flush()
    fileOutPut.close()
    return Uri.fromFile(tempFile)
}
4

The above solution uses media store and stores the image in the users main image folder making it viewable through the gallery/photo viewer. This solution will store it as a temporary file in your apps data. In this example inImage is a Bitmap and title is a string for the name of the image file.

    File tempDir= Environment.getExternalStorageDirectory();
    tempDir=new File(tempDir.getAbsolutePath()+"/.temp/");
    tempDir.mkdir();
    File tempFile = File.createTempFile(title, ".jpg", tempDir);
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    byte[] bitmapData = bytes.toByteArray();

    //write the bytes in file
    FileOutputStream fos = new FileOutputStream(tempFile);
    fos.write(bitmapData);
    fos.flush();
    fos.close();
    return Uri.fromFile(tempFile);
3
  • How temporary is temporary? When will the file be deleted? Can I use the same file name for several images in quick succession? Commented Mar 24, 2020 at 19:25
  • instead of tempDir=new File(tempDir.getAbsolutePath()+"/.temp/"); you can always use a directory exclusively used by your app.. and just leave the images there
    – DragonFire
    Commented Jun 23, 2020 at 5:02
  • @Joel Also if you are using in a loop name the file name as "file"+i and on success of your process like an api response you can clear this folder -> that will have to be done manually
    – DragonFire
    Commented Jun 23, 2020 at 5:19
2
val context = LocalContext.current
val uri = context.saveImage(bitmap) // here you will receive the Uri


private fun Context.saveImage(bitmap: Bitmap): Uri? {
    var uri: Uri? = null
    try {
        val fileName = System.nanoTime().toString() + ".png"
        val values = ContentValues().apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
            put(MediaStore.Images.Media.MIME_TYPE, "image/png")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM/")
                put(MediaStore.MediaColumns.IS_PENDING, 1)
            } else {
                val directory =
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
                val file = File(directory, fileName)
                put(MediaStore.MediaColumns.DATA, file.absolutePath)
            }
        }

        uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        uri?.let {
            contentResolver.openOutputStream(it).use { output ->
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, output)
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                values.apply {
                    clear()
                    put(MediaStore.Audio.Media.IS_PENDING, 0)
                }
                contentResolver.update(uri, values, null, null)
            }
        }
        return uri
    }catch (e: java.lang.Exception) {
        if (uri != null) {
            // Don't leave an orphan entry in the MediaStore
            contentResolver.delete(uri, null, null)
        }
        throw e
    }
}
1

pass bitmap and compressFormat like (PNG, JPG, etc...) and image quality in percentage

public Uri getImageUri(Bitmap src, Bitmap.CompressFormat format, int quality) {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    src.compress(format, quality, os);

    String path = MediaStore.Images.Media.insertImage(getContentResolver(), src, "title", null);
    return Uri.parse(path);
}
5
  • path can be null, so your code would crash on Uri.parse(path) Commented Aug 5, 2017 at 22:17
  • you check path is null or not. and after you pass in Uri Commented Aug 8, 2017 at 13:15
  • @PankajTalaviya This method is saving the image with .jpg format even we provide PNG format to compress. Commented Mar 1, 2019 at 9:31
  • @PankajMundra Increase decrease quality percentage to compress image Commented Mar 4, 2019 at 11:02
  • So according to you what should be the appropriate percentage to save image as .png...because if it saves as jpeg the background of image is black. Commented Mar 4, 2019 at 11:06
0

Well you can't transforma a bitmap file into a uri. Read more about URI here

URI is an Uniform Resource Identifier. But you can place the bitmap in an absolute or relative URI like this

Absolute: http://android.com/yourImage.bmp
Relative: yourImage.bmp 
2
  • then how can achieve my needs? it's impossible? Commented Nov 28, 2011 at 12:39
  • I guess you have to rethink your way to see this... check Facebook and twitter APIS to see how you can achieve that image sharing Commented Nov 28, 2011 at 13:58
0
String picName = "pic.jpg";
        String PATH = Environment.getExternalStorageDirectory().getPath()+ picName;
        File f = new File(PATH);
        Uri yourUri = Uri.fromFile(f);

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.