如何将位图图像转换为 Uri [英] How To Convert A Bitmap Image To Uri
问题描述
我没有在任何地方找到这个问题的答案.
I have not found the answer to this question anywhere.
Bitmap Image 是在应用程序中处理的,也就是说没有获取 Image 的文件路径.
The Bitmap Image is processed in The application, meaning there is no File path to get the Image.
下面是如何将 Uri 转换为 Bitmap
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 表示保存数据的位置.因此,如果您需要获取位图的 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 N 上使用 Uri
,您应该使用 FileProvider
来提供文件.按照 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屋!