【问题标题】:Sending email with image attachment发送带有图片附件的电子邮件
【发布时间】:2023-03-22 10:10:01
【问题描述】:

我需要使用 Android 共享意图发送一封电子邮件,其中包含需要使用网络请求获取的图像。

我发现的大多数执行此操作的示例都涉及已保存到设备的图像。

如果需要先获取图像,而不必将其保存到磁盘,我该如何实现?

我使用 Glide 作为我的图像加载器。

【问题讨论】:

  • 您首先应该下载图像。

标签: android share email-attachments


【解决方案1】:

您可以使用 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();。您可以删除该语句,因为它没有用,只会令人困惑。此外,您应该取消字节数组输出流并直接压缩到文件输出流。
  • 对于其余部分,此代码将下载的 png 文件转换为位图,然后将该位图转换回 png 文件。那是糟糕的编程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-23
  • 2015-09-09
  • 2011-01-14
相关资源
最近更新 更多