java - 如何通过信使从应用程序发送图像?
问题描述
我想通过信使从我的应用程序发送图像。我正在查看 Stack Overflow,我找到了适用于 WhatsApp 的答案。当我尝试将“com.whatsapp”更改为“com.facebook.orca”时,它停止工作。这是我的代码:
public void shareImageMessenger() {
Bitmap adv = BitmapFactory.decodeResource(getResources(), R.drawable.koza);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
adv.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "temporary_file_1.jpg");
try {
f.createNewFile();
new FileOutputStream(f).write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
share.putExtra(Intent.EXTRA_STREAM,
Uri.parse( Environment.getExternalStorageDirectory()+ File.separator+"temporary_file_1.jpg"));
share.setPackage("com.facebook.orca");
startActivity(Intent.createChooser(share, "Share Image"));
}
解决方案
在花了很多时间之后:
检查是否授予权限。然后:
第1步:在活动中创建你想要的图像的ImageView,然后将其转换为位图
ImageView imageView = findViewById(R.id.image);
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
//save the image now:
saveImage(bitmap);
//share it
send();
第 2 步:将图像存储在内部文件夹中:
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 (Exception e) {
e.printStackTrace();
}
}
第 3 步:发送保存的图像:
public void send() {
try {
File myFile = new File("/storage/emulated/0/saved_images/Image-test.jpg");
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext = myFile.getName().substring(myFile.getName().lastIndexOf(".") + 1);
String type = mime.getMimeTypeFromExtension(ext);
Intent sharingIntent = new Intent("android.intent.action.SEND");
sharingIntent.setType(type);
sharingIntent.putExtra("android.intent.extra.STREAM", Uri.fromFile(myFile));
startActivity(Intent.createChooser(sharingIntent, "Share using"));
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
现在发送后,如果您不希望保存的图像在您的存储中,您可以删除它。检查其他链接来做到这一点。
推荐阅读
- google-cloud-platform - 是否可以使用 google GCP API Gateway 将 IP 白名单列入白名单?
- powerbi - Power BI Dax 错误 - 表达式引用多个列。不能将多列转换为标量值
- python - 熊猫重复行替换一列值
- javascript - 无法从“app.js”安装,因为它不包含 package.json 文件
- android - 如何从 Android Kotlin 的库中访问“应用程序”信息
- html - 如何修复滚动条不是文本大小 HTML 的高度
- r - 使用条件组合在数据框中子集行
- go - 如果 Semaphore 阻塞时间过长,则打印消息,但在打印消息时不要取消阻塞调用者
- java - 'org.apache.commons.codec.binary.Hex' 中的 'decodeHex(char[])' 不能应用于 '(java.lang.String)'
- python - 使用 Python 从 HTML 网页中解析 JSON