我已经将Bitmap保存到内部存储中:
private String saveToInternalSorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(mContext);
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return directory.getAbsolutePath();
}
现在我想与它分享:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.putExtra(Intent.EXTRA_STREAM, file);
sharingIntent.setType("image/jpeg");
getContext().startActivity(Intent.createChooser(sharingIntent,"Erfolg teilen!"));
如何获取内部存储的位图并将其“制作”到“文件”,我可以共享?
我尝试加载它:
ContextWrapper cw = new ContextWrapper(mContext); File directory = cw.getFilesDir(); File file = new File(directory, "profile.jpg");
但这不起作用它显示没有图片,如果我想分享它(在Facebook它说它无法加载图像)。保存方法是否正确?
将mode_private
改为mode_world_readable
也改变:
File directory = cw.getFilesDir();
至 :
cw.getDir ("profile.jpg", Context.MODE_WORLD_READABLE);
我用一个Bitmap保存到内部存储
你的ContextWrapper
没有明显的价值。
如何获取内部存储的位图并将其“制作”到“文件”,我可以共享?
你已经将它作为一个文件。这就是saveToInternalSorage()
所做的。
为了让它可以分享,use FileProvider
。但是,您可能需要从getDir("imageDir", Context.MODE_PRIVATE)
切换到使用以getFilesDir()
为根的内容。
根据documentation EXTRA_STREAM应该包含一个URI,其中包含与Intent关联的数据流。
因此,在您的示例中使用Uri.fromFile(file)替换文件:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
sharingIntent.setType("image/jpeg");
您可能还需要授予此intent权限的收件人对URI执行读取操作:
sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
我遇到了这个问题。我使用Context.getFilesDir()
来保存我的位图(并避免请求写入权限)。您需要在清单中使用文件提供程序这是我的文件提供程序
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
我的路径,我使用一个名为Screenshots的子文件夹
<paths>
<files-path
name="my_images"
path="Screenshots/" />
</paths>
然后你可以使用这个意图来共享位图(Im suing kotlin)
val shareIntent = Intent(Intent.ACTION_SEND)
.apply {
type = "image/jpeg"
putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(applicationContext, BuildConfig.APPLICATION_ID, file))
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
startActivity(Intent.createChooser(shareIntent, "Share Image"));
更多信息:https://developer.android.com/reference/android/support/v4/content/FileProvider.html#Permissions