【问题标题】:Sending bitmap image from one activity to another将位图图像从一个活动发送到另一个活动
【发布时间】:2019-07-09 13:52:47
【问题描述】:

我有一个问题想问你一个关于位图图像从主活动的次要活动的通道的问题。在辅助活动中,我有一个 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");

问题是当我得到位图图像时,变量总是为空,我不能在imageView上设置它。我无法理解原因,因为如果我在辅助类中打印位图图像的值,它就存在。 谁能帮帮我。

提前致谢

【问题讨论】:

标签: android android-studio imageview


【解决方案1】:

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

字节数组。

创建位图的 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);

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

【讨论】:

【解决方案2】:

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

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

最好的第二个解决方案,因为有时发送字节数组会导致 OutOfMemory 当我们有大的 bitmap

时出现问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 2012-07-20
    相关资源
    最近更新 更多