将位图图像从一个活动传递到另一个活动

7
在我的应用程序中,我从图库中显示了许多图片。当我选择一张图片时,这张图片应该被发送到新的活动中,并设置为背景。然而,虽然我能够从图库中获取图片,但是一旦我选择一张图片,应用程序就会崩溃。提前感谢您的帮助。
第一个活动(图片在画廊中显示,所选图片被发送到新的活动中)。
public class Gallery extends Activity {

private static int RESULT_LOAD_IMAGE = 1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gallery);

        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);


        buttonLoadImage.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {

                Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
    }



    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {






            Uri contentUri = data.getData();          
            String[] proj = { MediaStore.Images.Media.DATA };         
            Cursor cursor = managedQuery(contentUri, proj, null, null, null);         
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);         
            cursor.moveToFirst();         
            String tmppath = cursor.getString(column_index);           
            Bitmap croppedImage = BitmapFactory.decodeFile(tmppath);


            // Bitmap croppedImage = BitmapFactory.decodeFile(croppedImage);
            Intent intent = new Intent(Gallery.this,GesturesActivity.class);
            intent.putExtra("bmp",croppedImage);
            startActivity(intent);

            Log.v("sending image","sending image");


        }


    }
}

活动-1(XML)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/background"
    >
    <ImageView
            android:id="@+id/imgView"
            android:layout_width="fill_parent"
            android:layout_weight="1" android:layout_height="wrap_content"></ImageView>
    <Button 
            android:layout_height="wrap_content" 
            android:text="Load Picture" 
            android:layout_width="wrap_content" 
            android:id="@+id/buttonLoadPicture" 
            android:layout_weight="0" 
            android:layout_gravity="center"></Button>
</LinearLayout>

活动-2(选择的图像应设置为屏幕的背景图像的活动)

  public class GesturesActivity extends Activity {


        private final int MENU_CAMERA = Menu.FIRST;


        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);


            Bitmap bmp = (Bitmap)this.getIntent().getParcelableExtra("bmp");
            BitmapDrawable background = new BitmapDrawable(bmp);
            getWindow().setBackgroundDrawable(background);  //background image of the screen



            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.advert);
            View view = new SandboxView(this, bitmap);

            setContentView(view);
        }



        public boolean onPrepareOptionsMenu(Menu menu) {
            menu.clear();

                menu.add(0, 11, 0, "Take Snapshot");

                    return super.onPrepareOptionsMenu(menu);
        }


        public boolean onOptionsItemSelected(MenuItem item) {

            return super.onOptionsItemSelected(item);
        }



    }

请查看这个链接 - Ram kiran Pachigolla
8个回答

21

解决此问题有三种方法。

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

将位图转换为字节数组:

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

将字节数组传递给意图(Intent):

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

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

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中。

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


根据您的第一种解决方案,如果我想将一个 ImageView 转换为 Bitmap,我该如何操作呢? - Akash Shah

7

既然您是从图库中检索图像,为什么不将id传递到下一个活动中,并在该活动中检索图像,而不是传递图像?这可以帮助您节省内存并提高性能。


3
+1,这是最方便的方法。存储用户选择的图像ID并将该ID传递到下一个活动。 - Sahil Mahajan Mj

5

位图(Bitmap)实现了Parcelable,因此您始终可以将其传递到意图中。请尝试以下代码:

第一个活动。

Intent mIntent = new Intent(this, ActivityTwo.class);
mIntent.putExtra("bmp_img", bmp);

如果想要在目标活动中获得输出,请尝试以下方法:

第二个活动。

Bitmap mBitmap = (Bitmap) intent.getParcelableExtra("bmp_img");

在Activity中,您始终使用 getParcelableExtra("key") 来获取传递的Bitmap。


1
@oren 大位图的替代方案是什么? - Anshul Tyagi
1
@AnshulTyagi 如果你正在处理大位图,你可以将它们保存到内部存储中,将文件名作为额外参数传递给第二个活动,然后从内部存储中读取。我用它来传输截屏,效果很好。 - markcheeky

2

活动

在活动之间传递位图

Intent intent = new Intent(this, Activity.class);
intent.putExtra("bitmap", bitmap);

而在Activity类中

Bitmap bitmap = getIntent().getParcelableExtra("bitmap");

片段

在片段之间传递位图

SecondFragment fragment = new SecondFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("bitmap", bitmap);
fragment.setArguments(bundle);

接收来自SecondFragment内部的内容

Bitmap bitmap = getArguments().getParcelable("bitmap");

如果你遇到了绑定事务失败的问题,这意味着你正在通过从一个活动传输大量元素来超出绑定事务缓冲区。

在这种情况下,你需要将位图压缩为字节数组,然后在另一个活动中解压缩它,像这样:

在第一个活动中:

Intent intent = new Intent(this, SecondActivity.class);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPG, 100, stream);
byte[] bytes = stream.toByteArray(); 
intent.putExtra("bitmapbytes",bytes);

在SecondActivity中

byte[] bytes = getIntent().getByteArrayExtra("bitmapbytes");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

1

使用此方法,您可以将位图传递到另一个活动中。

如果您正在使用Drawable,则首先将其转换为位图。

Bitmap bitmap = ((BitmapDrawable)d).getBitmap();

如果想通过意图将该位图传递给另一个活动,请使用下面的代码片段。

intent.putExtra("Bitmap", bitmap);

如果想在另一个活动中获取位图意图,请使用以下代码:

Bitmap bitmap = (Bitmap)this.getIntent().getParcelableExtra("Bitmap");

1

我认为你可以将Bitmap定义为静态的,通过调用classname.bitmap来获取位图,并在下一个Activity中将其设置为背景。


0

我发现最简单(但绝对不是最优雅)的方法是使用静态类成员。例如:

class PassedData
{
    public Bitmap bm1, bm2, etc;

    private PassedData current;

    public static PassedData getCurrent() {return current;}

    public PassedData()
    {
        current = this;
    }
}

然后每个活动都可以引用PassedData.getCurrent()。

0

IGP已经清楚地总结了,但在我看来,最有效的方法是将图像的URI传递给下一个活动,而不是Bitmap本身。实际上,我不确定是否可以使用Intents从一个活动传递整个位图(或转换为ByteArrays)的数据到另一个活动 - 我相信Bundle可以包含多少数据有限制。

相反,传递您在第一个活动中用于显示图像的引用。我假设您正在使用某种懒加载?如果没有,我强烈建议您这样做。这样,您可以通过URI简单地重新查询位图。

然而,我能够从画廊获取图像,但是一旦我选择一个应用程序就会崩溃

我仍然对这些问题如何达到SO感到困惑。检查日志,也许您可以自己解决它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接