How To Convert A Bitmap Image To Uri

僤鯓⒐⒋嵵緔 提交于 2019-11-29 11:56:42

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!