【发布时间】:2023-03-22 10:10:01
【问题描述】:
我需要使用 Android 共享意图发送一封电子邮件,其中包含需要使用网络请求获取的图像。
我发现的大多数执行此操作的示例都涉及已保存到设备的图像。
如果需要先获取图像,而不必将其保存到磁盘,我该如何实现?
我使用 Glide 作为我的图像加载器。
【问题讨论】:
-
您首先应该下载图像。
标签: android share email-attachments
我需要使用 Android 共享意图发送一封电子邮件,其中包含需要使用网络请求获取的图像。
我发现的大多数执行此操作的示例都涉及已保存到设备的图像。
如果需要先获取图像,而不必将其保存到磁盘,我该如何实现?
我使用 Glide 作为我的图像加载器。
【问题讨论】:
标签: android share email-attachments
您可以使用 glide 将图像保存到缓存目录中,并使用以下代码将其作为附件发送
Glide
.with(getApplicationContext())
.load("https://www.google.es/images/srpr/logo11w.png") // your URL
.asBitmap()
.into(new SimpleTarget<Bitmap>(100,100) {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
File f = new File(context.getCacheDir(), filename);// use your filename fully
f.createNewFile();
//Convert bitmap to byte array
Bitmap bitmap = resource;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
Uri U = Uri.fromFile(f);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("image/png");
i.putExtra(Intent.EXTRA_STREAM, U);
startActivity(Intent.createChooser(i,"Email:"));
}
});
【讨论】:
f.createNewFile();。您可以删除该语句,因为它没有用,只会令人困惑。此外,您应该取消字节数组输出流并直接压缩到文件输出流。