繁体   English   中英

安卓 分享图片错误

[英]Android. Sharing image error

我编写了以某种方式处理图像的应用程序,然后我想共享它。 意味着允许用户使用标准共享活动来共享它。 当我这样做时,我会收到错误消息。 当我选择Gmail时,它写为Can't open empty file 但是文件已保存,我可以使用Gallery或任何其他应用程序将其打开。 因此我无法弄清楚我做错了什么。

这是我的共享代码:

public static void shareImage(Bitmap bmp, Context context) {

    String pathBitmap = saveBitmap(bmp, context);
    if (pathBitmap == null) {
        Toast.makeText(context, context.getResources().getString(R.string.save_photo_failed), Toast.LENGTH_SHORT).show();
        return;
    }

    Uri bitmapUri = Uri.parse(pathBitmap);
    if (bitmapUri != null) {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("image/png");
        shareIntent.putExtra(Intent.EXTRA_STREAM, bitmapUri);
        context.startActivity(Intent.createChooser(shareIntent, "Share"));
    }
}

这是我保存位图的方法:

public static String saveBitmap(Bitmap bmp, Context context) {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSS");
    String fileName   = sdf.format(new Date(System.currentTimeMillis()));
    File fNew = new File(MyApp.getInstance().getPhotosPath(), fileName + ".png");

    FileOutputStream out = null;
    try {
        out = new FileOutputStream(fNew);
        bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
        // PNG is a lossless format, the compression factor (100) is ignored
        out.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
    Toast.makeText(context, context.getResources().getString(R.string.photos_saved), Toast.LENGTH_SHORT).show();
    return fNew.getAbsolutePath();
}

更新

这里是返回路径的函数。 从应用程序onCreate()调用createFolder() onCreate()

private void createFolder() {

    _pathPhotos = "";
    try {
        File folder = new File(Environment.getExternalStorageDirectory(), "WonderApp");
        folder.mkdir();
        _pathPhotos = folder.getAbsolutePath();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

public String getPhotosPath() {
    return _pathPhotos;
}

代码有什么问题?

最后,我解决了这个问题。 问题实际上是在这里描述的。 正如GuiFGDeo所写的那样,问题在于URI应该是内容URI,而不是文件URI。 在这里,您可以找到Google提出的解决问题的建议。 我发现了一个更短的方法。

将图像插入媒体存储区时,您收到的正是您所需要的内容URI。 和瞧!

public static void shareImage(Bitmap bmp, Context context) {

    String sImageUrl = MediaStore.Images.Media.insertImage(context.getContentResolver(), bmp, "title" , "description");
    Uri savedImageURI = Uri.parse(sImageUrl);

    if (savedImageURI != null) {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("image/jpg");
        shareIntent.putExtra(Intent.EXTRA_STREAM, savedImageURI);
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        context.startActivity(Intent.createChooser(shareIntent, "Share"));
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM