如何将带有图片的文件从应用程序发送到E-mail或whatsapp(25.10.2021)



对于类似的问题,我尝试了大约10个答案,但没有一个是成功的。有些东西可能过时了。请给出今天的答案。

简单的任务:我希望我的应用程序能够发送一个带有图像的文件到电子邮件或whatsapp。

我将带有图像的文件放在应用程序资源文件夹Drawable中。文件大小为5mb。

如何在Java中做到这一点?

我要求代码,而不是链接到类似的答案。大部分我都试过了。

一些决定来到null.bin。有些根本不发送任何东西,并抛出错误。

也许我没有指定任何权限。还有别的可能。我是新的。我想要一个有评论的回答(我在写什么和为什么)

// step 1. I put the picture in the folder Drawable

// clicking on the button sends the picture through the messenger to other users

public void onClick_sendMyImage(View v) {

// Step 2.Convert PICTURE to Bitmap
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image1);
saveImage(bitmap);   // 3. save the PICTURE in the internal folder
send();              // 4.sending PICTURE (function code below)
}


// step 3. Saving the image in the internal folder:
private static void saveImage(Bitmap finalBitmap){
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root + "/saved_images");
//Log.i("Directory", "==" + myDir);
myDir.mkdirs();

String fname = "image_test" + ".jpg";
File file = new File(myDir, fname);
if(file.exists()) file.delete();
try{
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

// Step 4. Sending the saved PICTURE
public void send(){
try{
File myFile = new File("/storage/emulated/0/saved_images/image_test.jpg");
// for something I create this type (so it is said in one of the answers)
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext = myFile.getName().substring(myFile.getName().lastIndexOf(".") + 1);
String type = mime.getMimeTypeFromExtension(ext);

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType(type);

intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(myFile));
Intent intent1 = Intent.createChooser(intent, "what do you want to send ?");
startActivity(intent1);

}catch (Exception e){
Toast.makeText(this, "repeat sending", Toast.LENGTH_SHORT).show();
}

}

从应用程序发送图像被证明不是一个好主意。

  1. 如果需要,该图像不能编辑。
  2. 随着时间的推移,你可能想添加更多的图像,等等。

我做了不同的,结果更好:

  1. 我把图像放在GoogleDisk上。现在我可以随时更改,而不需要要求用户在每次图片更改时重新安装应用程序)。

  2. 我在FireBase数据库中放置了指向图片的链接。(我还在这里放了一个带图片的横幅).

  3. 我将应用程序连接到Firebase数据库。

  4. 在活动中,我做了一个recyingview,在那里我得到了一个横幅和一个链接到原始图像(s)。用户可以下载此链接或通过whatsapp发送到任何地方,并下载高质量的原始图片(A1, 2.5Mb)。


谢谢,男人. .

我感谢这些家伙的提示,尤其是mr.Blackapps。在这种情况下,你真的不能没有FileProvider。

最新更新