我正在创建一个应用程序,允许用户使用android意图共享图像,但如何获取
的URI位图,无需将其保存到SD卡
我使用的代码工作正常,但我不需要将此位图保存到SD卡
private Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "title", null);
return Uri.parse(path);
}
我需要获取该URI而不将该位图保存到SD卡
答案 0 :(得分:18)
试试这个:
protected void ShareImage(Intent intent) {
try {
URL url = new URL(mImageUrl);
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
intent.putExtra(Intent.EXTRA_STREAM, getImageUri(mActivity, image));
} catch (Exception e) {
e.printStackTrace();
}
startActivityForResult(Intent.createChooser(intent, 1001));
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
//check for result is OK and then check for your requestCode(1001) and then delete the file
}
答案 1 :(得分:1)
试试这种方式
protected void tryToShareImage(Intent intent) {
try {
URL url = new URL(mImageUrl);
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
intent.putExtra(Intent.EXTRA_STREAM, getImageUri(mActivity, image));
} catch (Exception e) {
e.printStackTrace();
}
startActivity(Intent.createChooser(intent, "Share using..."));
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
之后您可以使用File.delete()
答案 2 :(得分:0)
接受的答案对我不起作用。也许我错过了一些东西。但是,每次我获取位图的 uri 时,它都会保存在本地存储中。我找不到在接受的答案中删除(额外)保存的位图的方法。 我正在使用以下方式:
首先获取位图的uri:
public static Uri getUri(Context context, Bitmap bitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmap, "Title", null);
return Uri.parse(path);
}
然后,删除(额外)保存的位图:
this.getContentResolver().delete(uri, null, null);
PS:上面的删除代码是针对Activity的。如果要在 Fragment 内删除,请使用:
getActivity().getContentResolver().delete(uri, null, null);