如何在不保存时如何压缩位图



我从布局中获得图片,不想保存它。我想通过意图ACTION_SEND服务直接分享它。当我发送时给出异常Transaction Too many Large: data parcel size 2315980 bytes

这是我的代码片段

View myview = (View) findViewById(R.id.mylayout);
Bitmap mypicture = getBitmapFromView(myview);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra("", mypicture);
intent.setType("image/jpeg");
startActivity(intent);

我想直接通过Intent Action_Send Service分享它

这不是一个选择。EXTRA_TEXT包含文本。EXTRA_STREAM容纳Uri。这些都不是Bitmap

这是我的代码片段

您的额外是毫无意义的,因为没有ACTION_SEND的活动将使用一个空钥匙寻找额外的活动。

您可以将位图保存到文件中,然后共享URI/链接到该文件。

public static File saveBitmapInternal(Context context, Bitmap bitmap) {
    File imagePath = new File(context.getFilesDir(), "images");
    if (!imagePath.exists() && !imagePath.mkdirs()) {
        print("Make dir failed");
    }
    return saveBitmap(bitmap, "preview.png", imagePath);
}

private static File saveBitmap(Bitmap bitmap, String filename, File root) {
    print(String.format("Saving %dx%d bitmap to %s.", bitmap.getWidth(), bitmap.getHeight(), filename));
    final File file = new File(root, filename);
    if (file.exists()) {
        file.delete();
    }
    try {
        final FileOutputStream out = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.PNG, 99, out);
        out.flush();
        out.close();
        return file;
    } catch (final Exception e) {
        print("Exception!" + e);
    }
    return null;
}

然后分享它,

        // Uri uri = Uri.fromFile(file);
        Uri uri = FileProvider.getUriForFile(context,
                context.getString(R.string.file_provider_authority),
                file);
        final Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        intent.putExtra(Intent.EXTRA_TEXT, shareText);
        context.startActivity(Intent.createChooser(intent, "Share media"));

您需要在清单中设置文件提供商(请参阅https://developer.android.com/reference/reference/android/support/v4/content/content/fileprovider.html)。如果您对FileProvider有疑问,则可以创建另一个问题。

最新更新