How To Convert A Bitmap Image To Uri

前端 未结 2 573
悲哀的现实
悲哀的现实 2020-12-18 11:55

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.

Belo

相关标签:
2条回答
  • 2020-12-18 12:37

    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.

    0 讨论(0)
  • 2020-12-18 12:42

    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.

    0 讨论(0)
提交回复
热议问题