How can I transform a Bitmap into a Uri?
Asked Answered
B

8

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?

Bundesrat answered 28/11, 2011 at 12:25 Comment(0)
F
23
String FILENAME = "image.png";
String PATH = "/mnt/sdcard/"+ FILENAME;
File f = new File(PATH);
Uri yourUri = Uri.fromFile(f);
Farthingale answered 28/11, 2011 at 13:58 Comment(5)
Parse always take as argument a String not a file. Next time read details about functions or maybe test them.Balanchine
can't we get Uri without saving the bitmapEllmyer
work in android studio 2022 bumblebeeWrapped
@rezarahmad Dear sheldon, This was answered 10 years back,Farthingale
@Farthingale yes this still working until 2023 and more future yearsWrapped
A
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);
}
Antevert answered 23/4, 2013 at 11:22 Comment(9)
Note this creates an image that will stick around in the users gallery.Grisham
path can be null, if so, Uri.parse(path) will make app crashTilla
Dont forget to take WRITE_EXTERNAL_STORAGE permission. Otherwise insertImage method may return null. See : https://mcmap.net/q/357075/-mediastore-images-media-insertimage-return-null-sometimesTaneka
@Noman If you want to delete inserted image, you can look at https://mcmap.net/q/73848/-convert-file-uri-to-file-in-androidTaneka
Not workking in android oreo, String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null); path will get null.Avantgarde
The background of my image became black. How to make the background transparent?Palmitate
This method is deprecatedOrtiz
@Palmitate did you figured out how to get rid of that black background?Boxboard
@Antevert you're a bossGreensward
F
23
String FILENAME = "image.png";
String PATH = "/mnt/sdcard/"+ FILENAME;
File f = new File(PATH);
Uri yourUri = Uri.fromFile(f);
Farthingale answered 28/11, 2011 at 13:58 Comment(5)
Parse always take as argument a String not a file. Next time read details about functions or maybe test them.Balanchine
can't we get Uri without saving the bitmapEllmyer
work in android studio 2022 bumblebeeWrapped
@rezarahmad Dear sheldon, This was answered 10 years back,Farthingale
@Farthingale yes this still working until 2023 and more future yearsWrapped
O
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)
}
Odoric answered 30/8, 2022 at 18:57 Comment(0)
G
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);
Grisham answered 11/3, 2016 at 17:52 Comment(3)
How temporary is temporary? When will the file be deleted? Can I use the same file name for several images in quick succession?Ambrogio
instead of tempDir=new File(tempDir.getAbsolutePath()+"/.temp/"); you can always use a directory exclusively used by your app.. and just leave the images thereLenoir
@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 manuallyLenoir
E
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
    }
}
Endoskeleton answered 29/8, 2022 at 4:33 Comment(0)
A
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);
}
Annapurna answered 17/2, 2017 at 8:50 Comment(5)
path can be null, so your code would crash on Uri.parse(path)Tilla
you check path is null or not. and after you pass in UriAnnapurna
@PankajTalaviya This method is saving the image with .jpg format even we provide PNG format to compress.Hardaway
@PankajMundra Increase decrease quality percentage to compress imageAnnapurna
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.Hardaway
B
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 
Balanchine answered 28/11, 2011 at 12:36 Comment(2)
then how can achieve my needs? it's impossible?Bundesrat
I guess you have to rethink your way to see this... check Facebook and twitter APIS to see how you can achieve that image sharingBalanchine
L
0
String picName = "pic.jpg";
        String PATH = Environment.getExternalStorageDirectory().getPath()+ picName;
        File f = new File(PATH);
        Uri yourUri = Uri.fromFile(f);
Lythraceous answered 13/4, 2016 at 9:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.