我正在尝试获取视图的图像(约束布局)并通过 android 发送意图共享它。
我尝试了很多方法,但直到现在都没有奏效。这是我到目前为止所拥有的:
public void shareStatsImage(){
constraintLayout.setDrawingCacheEnabled(true);
Bitmap bitmap = constraintLayout.getDrawingCache();
File path = null;
try {
path = saveImageToExternal(generateImageTitle(), bitmap);
} catch (IOException e) {
e.printStackTrace();
}
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/png");
final File photoFile = new File(Objects.requireNonNull(getActivity()).getFilesDir(), Objects.requireNonNull(path).getAbsolutePath());
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(photoFile));
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Share image using"));
}
public static String generateImageTitle(){
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss");
return sdf.format(new Date());
}
public File saveImageToExternal(String imgName, Bitmap bm) throws IOException {
//Create Path to save Image
String appFolder = "test";
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + File.separator + appFolder); //Creates app specific folder
path.mkdirs();
File imageFile = new File(path, imgName+".png"); // Imagename.png
FileOutputStream out = new FileOutputStream(imageFile);
try{
bm.compress(Bitmap.CompressFormat.PNG, 100, out); // Compress Image
out.flush();
out.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(getContext(),new String[] { imageFile.getAbsolutePath() }, null,new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch(Exception e) {
throw new IOException();
}
return imageFile;
}
此解决方案存在多个问题,例如,在将图像共享到 gmail 时,我收到一条错误消息(“附件的权限被拒绝”)。将图像上传到谷歌驱动器时,我只会收到“上传失败消息”。
一件好事是图像似乎出现在手机的图库中,而不是在通过意图共享它们时出现:(
谢谢你的帮助!