如何将位图图像转换为Uri [英] How To Convert A Bitmap Image To Uri

查看:102
本文介绍了如何将位图图像转换为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.

下面是如何将Uri转换为位图

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);
    }

我现在如何转换为Uri

How do I now reconvert to a Uri

推荐答案

URI是URL的超集,这意味着它是文件的路径.而位图是由点矩阵组成的数字图像.位图表示数据,uri表示保存数据的位置.SO,如果您需要获取位图的URI,只需将其保存在存储上.在android中,您可以通过Java IO进行操作,如下所示:首先在要保存的位置创建文件:

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;
}

然后冲洗它,您将获得URi

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);
}

这只是所有Android版本的非空闲代码示例.要在Android N上和Android N上使用Uri,您应该使用 来提供文件.遵循Commonsware的答案.

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.

这篇关于如何将位图图像转换为Uri的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆