将位图图像从一个活动发送到另一个活动

时间:2019-07-09 13:52:47

标签: android android-studio imageview

我有一个问题要问您一个有关从主活动的次要活动传来位图图像的问题。在辅助活动中,我有一个videoView,我设置了一个按钮,当按下该按钮时,会从videoView中提取帧。我用于以位图格式提取帧的代码如下:

 videoField.setDrawingCacheEnabled(true);
            videoField.buildDrawingCache();
            Bitmap bm = videoField.getDrawingCache();
            System.out.println(bm);
            Intent intent = new Intent(this, MainActivity.class);
            intent.putExtra("BitmapImage", bm);
            startActivity(intent);

在主Activity的onCreate()中执行此操作后,按如下所示获取位图图像:

Intent intent = getIntent();
    Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");

问题在于,当我获取位图图像时,变量始终为null,并且无法在imageView上进行设置。我不明白原因,因为如果我在辅助类中打印位图图像的值,它就会存在。 有人可以帮我吗?

预先感谢

2 个答案:

答案 0 :(得分:2)

有两种方法可以将Bitmap从一个活动发送到另一个活动。

ByteArray。

创建位图的byteArray并通过Intent发送。

ByteArrayOutputStream bStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bStream);
byte[] byteArray = bStream.toByteArray();

Intent anotherIntent = new Intent(this, anotherActivity.class);
anotherIntent.putExtra("image", byteArray);
startActivity(anotherIntent);

在您的其他活动中,

Bitmap bmp;

byte[] byteArray = getIntent().getByteArrayExtra("image");
bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

注意:此方法并不理想,因为您可以在Intent中传递的数据限制为1MB。因此,如果数据超过1MB,它将崩溃。

有一种更安全的方法。

Uri /文件

1将位图另存为图像在应用程序的缓存目录中。这将为您提供文件的Uri。通过Intent传递此Uri。

val file = File(context.filesDir, name)
context.openFileOutput(file.name, Context.MODE_PRIVATE).use {
    it.write(bStream.toByteArray())
}

现在,您可以通过Intent传递name

2在您的下一个活动中,从Intent中获取Uri并加载位图。

val file = File(context.filesDir, name)
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(file, options);

这是一种将位图从一个活动传递到另一个活动的更安全的方法。

答案 1 :(得分:0)

解决方案1 ​​ 将其转换为Byte数组并有意传递

解决方案2 将位图存储在内存中,然后按意图传递文件路径,并在下一个活动中访问该文件

最佳解决方案,因为一段时间发送字节数组会导致 OutOfMemory ,当我们有大量 bitmap

时会出现问题
相关问题