将图像从一个活动传递到另一个活动 [英] Passing image from one activity another activity

查看:36
本文介绍了将图像从一个活动传递到另一个活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SO 上有类似的问题,但没有一个对我有用.

There are similar questions on SO, but none worked for me.

我想在 Activity1 中获取点击的图像并将其显示在 Activity2 中.
我正在获取点击图像的图像 ID,如下所示:

I want to fetch clicked image in Activity1 and display it in Activity2.
I'm fetching image id of clicked image like this:

((ImageView) v).getId()

并通过意图将其传递给另一个活动.

and passing it through intent to another activity.

在第二个活动中,我使用图像 ID 如下:

In 2nd activity, I use image id as following:

imageView.setImageResource(imgId);

我在两个活动中都记录了值 og 图像 id,它是相同的.

I logged the value og image id in both the activities and it's same.

但我收到以下异常:

android.content.res.Resources$NotFoundException: Resource is not a Drawable 
(color or path): TypedValue{t=0x12/d=0x0 a=2 r=0x7f050000}

我猜这里的问题是 getId() 返回的是 ImageView 的 ID 而不是它的源图像.
所有这些图像都存在于 drawable 中.

I guess the problem here is getId() is returning Id of ImageView and not of it's source image.
All these images are present in drawable.

感谢任何帮助.

推荐答案

有 3 个解决方案可以解决此问题.

There are 3 Solutions to solve this issue.

1) 首先将图像转换为字节数组,然后传入 Intent,在下一个活动中从 Bundle 中获取字节数组并转换为图像(位图)并设置为 ImageView.

1) First Convert Image into Byte Array and then pass into Intent and in next activity get byte array from Bundle and Convert into Image(Bitmap) and set into ImageView.

将位图转换为字节数组:-

Convert Bitmap to Byte Array:-

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

将字节数组传递给意图:-

Pass byte array into intent:-

Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("picture", byteArray);
startActivity(intent);

从 Bundle 中获取字节数组并转换为位图图像:-

Get Byte Array from Bundle and Convert into Bitmap Image:-

Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("picture");

Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.imageView1);

image.setImageBitmap(bmp);

2) 首先将图像保存到 SDCard 中,然后在下一个活动中将此图像设置为 ImageView.

2) First Save image into SDCard and in next activity set this image into ImageView.

3) 将 Bitmap 传递到 Intent 并从 bundle 中获取下一个活动中的位图,但问题是如果当时您的 Bitmap/Image 尺寸很大,则图像不会在下一个活动中加载.

3) Pass Bitmap into Intent and get bitmap in next activity from bundle, but the problem is if your Bitmap/Image size is big at that time the image is not load in next activity.

这篇关于将图像从一个活动传递到另一个活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆