Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Convert A Bitmap Image To Uri

I have not found the answer to this question anywhere.

The Bitmap Image is processed in The application, meaning there is no File path to get the Image.

Below is how to convert a Uri to Bitmap

 if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
        Uri selectedImageUri = data.getData();

        imageview.setImageURI(selectedImageUri);

        try {
            bitmap1 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "" + e, Toast.LENGTH_SHORT).show();
        }

        bitmap1.compress(Bitmap.CompressFormat.JPEG, 7, bytearrayoutputstream);

        BYTE = bytearrayoutputstream.toByteArray();

        bitmap2 = BitmapFactory.decodeByteArray(BYTE, 0, BYTE.length);

        imagetoo.setImageBitmap(bitmap2);
    }

How do I now reconvert to a Uri

like image 711
Lucem Avatar asked Dec 02 '22 13:12

Lucem


2 Answers

URI is super set of URL that means its a path to file . whereas Bitmap is a digital image composed of a matrix of dots.Bitmap represents a data and uri represents that location where data is saved .SO if you need to get a URI for a bitmap You just need to save it on a storage . In android you can do it by Java IO like below:First Create a file where you want to save it :

public File createImageFile() {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File mFileTemp = null;
    String root=activity.getDir("my_sub_dir",Context.MODE_PRIVATE).getAbsolutePath();
    File myDir = new File(root + "/Img");
    if(!myDir.exists()){
        myDir.mkdirs();
    }
    try {
        mFileTemp=File.createTempFile(imageFileName,".jpg",myDir.getAbsoluteFile());
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return mFileTemp;
}

Then flush it and you will get the URi

 File file = createImageFile(context);
 if (file != null) {
    FileOutputStream fout;
    try {
        fout = new FileOutputStream(file);
        currentImage.compress(Bitmap.CompressFormat.PNG, 70, fout);
        fout.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }
    Uri uri=Uri.fromFile(file);
}

This is just an example not idle code for all android version. To use Uri above and on android N you should use FileProvider to serve the file . Follow the Commonsware's answer.

like image 90
ADM Avatar answered Dec 06 '22 12:12

ADM


Use compress() on Bitmap to write the bitmap to a file. Then, most likely, use FileProvider to serve that file, where getUriForFile() gives you the Uri corresponding to the file.

IOW, you do not "convert" a bitmap to a Uri. You save the bitmap somewhere that gives you a Uri.

like image 27
CommonsWare Avatar answered Dec 06 '22 12:12

CommonsWare