如何将位图对象从一个活动传递到另一个活动?

时间:2022-04-08 19:15:26

In my activity, I create a Bitmap object and then I need to launch another Activity, How can I pass this Bitmap object from the sub-activity (the one which is going to be launched)?

在我的活动中,我创建一个位图对象,然后我需要启动另一个活动,如何从子活动(即将启动的活动)传递这个位图对象?

8 个解决方案

#1


261  

Bitmap implements Parcelable, so you could always pass it with the intent:

位图实现了可分割性,所以您总是可以传递它的意图:

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

and retrieve it on the other end:

并在另一端检索:

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

#2


19  

Actually, passing a bitmap as a Parcelable will result in a "JAVA BINDER FAILURE" error. Try passing the bitmap as a byte array and building it for display in the next activity.

实际上,将位图作为可分配的传递将导致“JAVA绑定失败”错误。尝试将位图作为字节数组传递,并构建它以便在下一个活动中显示。

I shared my solution here:
how do you pass images (bitmaps) between android activities using bundles?

我在这里分享了我的解决方案:如何使用bundle在android活动之间传递图像(位图)?

#3


8  

Passsing bitmap as parceable in bundle between activity is not a good idea because of size limitation of Parceable(1mb). You can store the bitmap in a file in internal storage and retrieve the stored bitmap in several activities. Here's some sample code.

由于parceable (1mb)的大小限制,在活动之间将位图作为分组进行分组传递不是一个好主意。您可以在内部存储的文件中存储位图,并在多个活动中检索存储的位图。这里有一些示例代码。

To store bitmap in a file myImage in internal storage:

将位图存储在内部存储的myfile映像中:

public String createImageFromBitmap(Bitmap bitmap) {
    String fileName = "myImage";//no .png or .jpg needed
    try {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
        fo.write(bytes.toByteArray());
        // remember close file output
        fo.close();
    } catch (Exception e) {
        e.printStackTrace();
        fileName = null;
    }
    return fileName;
}

Then in the next activity you can decode this file myImage to a bitmap using following code:

然后在下一个活动中,您可以使用以下代码将这个文件myImage解码到位图:

Bitmap bitmap = BitmapFactory.decodeStream(context
                    .openFileInput("myImage"));//here context can be anything like getActivity() for fragment, this or MainActivity.this

Note A lot of checking for null and scaling bitmap's is ommited.

注意,很多对null和缩放位图的检查都被省略了。

#4


4  

If the image is too large and you can't save&load it to the storage, you should consider just using a global static reference to the bitmap (inside the receiving activity), which will be reset to null on onDestory, only if "isChangingConfigurations" returns true.

如果图像太大,无法保存并加载到存储中,您应该考虑使用位图的全局静态引用(在接收活动中),只有当“isChangingConfigurations”返回true时,该位图将在onDestory上重置为null。

#5


3  

Because Intent has size limit . I use public static object to do pass bitmap from service to broadcast ....

因为意图有大小限制。我使用公共静态对象通过位图从服务广播....

public class ImageBox {
    public static Queue<Bitmap> mQ = new LinkedBlockingQueue<Bitmap>(); 
}

pass in my service

通过我的服务

private void downloadFile(final String url){
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                Bitmap b = BitmapFromURL.getBitmapFromURL(url);
                synchronized (this){
                    TaskCount--;
                }
                Intent i = new Intent(ACTION_ON_GET_IMAGE);
                ImageBox.mQ.offer(b);
                sendBroadcast(i);
                if(TaskCount<=0)stopSelf();
            }
        });
    }

My BroadcastReceiver

我BroadcastReceiver

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            LOG.d(TAG, "BroadcastReceiver get broadcast");

            String action = intent.getAction();
            if (DownLoadImageService.ACTION_ON_GET_IMAGE.equals(action)) {
                Bitmap b = ImageBox.mQ.poll();
                if(b==null)return;
                if(mListener!=null)mListener.OnGetImage(b);
            }
        }
    };

#6


0  

It might be late but can help. On the first fragment or activity do declare a class...for example

可能会晚些,但会有所帮助。在第一个片段或活动中,请声明一个类……例如

   @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        description des = new description();

        if (requestCode == PICK_IMAGE_REQUEST && data != null && data.getData() != null) {
            filePath = data.getData();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);
                imageView.setImageBitmap(bitmap);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                constan.photoMap = bitmap;
            } catch (IOException e) {
                e.printStackTrace();
            }
       }
    }

public static class constan {
    public static Bitmap photoMap = null;
    public static String namePass = null;
}

Then on the second class/fragment do this..

然后在第二类/片段中做这个。

Bitmap bm = postFragment.constan.photoMap;
final String itemName = postFragment.constan.namePass;

Hope it helps.

希望它可以帮助。

#7


0  

You can create a bitmap transfer. try this....

您可以创建位图传输。试试这个....

In the first class:

在第一节课:

1) Create:

1)创建:

private static Bitmap bitmap_transfer;

2) Create getter and setter

2)创建getter和setter

public static Bitmap getBitmap_transfer() {
    return bitmap_transfer;
}

public static void setBitmap_transfer(Bitmap bitmap_transfer_param) {
    bitmap_transfer = bitmap_transfer_param;
}

3) Set the image:

3)设置图片:

ImageView image = (ImageView) view.findViewById(R.id.image);
image.buildDrawingCache();
setBitmap_transfer(image.getDrawingCache());

Then, in the second class:

然后,在第二节课:

ImageView image2 = (ImageView) view.findViewById(R.id.img2);
imagem2.setImageDrawable(new BitmapDrawable(getResources(), classe1.getBitmap_transfer()));

#8


-2  

In my case, the way mentioned above didn't worked for me. Every time I put the bitmap in the intent, the 2nd activity didn't start. The same happened when I passed the bitmap as byte[].

就我而言,上面提到的方法对我不起作用。每次我把位图放在意图中,第二个活动就没有开始。当我以byte[]传递位图时,也发生了同样的情况。

I followed this link and it worked like a charme and very fast:

我沿着这个链接,它就像一个魔术,非常快:

package your.packagename

import android.graphics.Bitmap;

public class CommonResources { 
      public static Bitmap photoFinishBitmap = null;
}

in my 1st acitiviy:

在我acitiviy 1:

Constants.photoFinishBitmap = photoFinishBitmap;
Intent intent = new Intent(mContext, ImageViewerActivity.class);
startActivity(intent);

and here is the onCreate() of my 2nd Activity:

这是我的第二个活动onCreate()

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bitmap photo = Constants.photoFinishBitmap;
    if (photo != null) {
        mViewHolder.imageViewerImage.setImageDrawable(new BitmapDrawable(getResources(), photo));
    }
}

#1


261  

Bitmap implements Parcelable, so you could always pass it with the intent:

位图实现了可分割性,所以您总是可以传递它的意图:

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

and retrieve it on the other end:

并在另一端检索:

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

#2


19  

Actually, passing a bitmap as a Parcelable will result in a "JAVA BINDER FAILURE" error. Try passing the bitmap as a byte array and building it for display in the next activity.

实际上,将位图作为可分配的传递将导致“JAVA绑定失败”错误。尝试将位图作为字节数组传递,并构建它以便在下一个活动中显示。

I shared my solution here:
how do you pass images (bitmaps) between android activities using bundles?

我在这里分享了我的解决方案:如何使用bundle在android活动之间传递图像(位图)?

#3


8  

Passsing bitmap as parceable in bundle between activity is not a good idea because of size limitation of Parceable(1mb). You can store the bitmap in a file in internal storage and retrieve the stored bitmap in several activities. Here's some sample code.

由于parceable (1mb)的大小限制,在活动之间将位图作为分组进行分组传递不是一个好主意。您可以在内部存储的文件中存储位图,并在多个活动中检索存储的位图。这里有一些示例代码。

To store bitmap in a file myImage in internal storage:

将位图存储在内部存储的myfile映像中:

public String createImageFromBitmap(Bitmap bitmap) {
    String fileName = "myImage";//no .png or .jpg needed
    try {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
        fo.write(bytes.toByteArray());
        // remember close file output
        fo.close();
    } catch (Exception e) {
        e.printStackTrace();
        fileName = null;
    }
    return fileName;
}

Then in the next activity you can decode this file myImage to a bitmap using following code:

然后在下一个活动中,您可以使用以下代码将这个文件myImage解码到位图:

Bitmap bitmap = BitmapFactory.decodeStream(context
                    .openFileInput("myImage"));//here context can be anything like getActivity() for fragment, this or MainActivity.this

Note A lot of checking for null and scaling bitmap's is ommited.

注意,很多对null和缩放位图的检查都被省略了。

#4


4  

If the image is too large and you can't save&load it to the storage, you should consider just using a global static reference to the bitmap (inside the receiving activity), which will be reset to null on onDestory, only if "isChangingConfigurations" returns true.

如果图像太大,无法保存并加载到存储中,您应该考虑使用位图的全局静态引用(在接收活动中),只有当“isChangingConfigurations”返回true时,该位图将在onDestory上重置为null。

#5


3  

Because Intent has size limit . I use public static object to do pass bitmap from service to broadcast ....

因为意图有大小限制。我使用公共静态对象通过位图从服务广播....

public class ImageBox {
    public static Queue<Bitmap> mQ = new LinkedBlockingQueue<Bitmap>(); 
}

pass in my service

通过我的服务

private void downloadFile(final String url){
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                Bitmap b = BitmapFromURL.getBitmapFromURL(url);
                synchronized (this){
                    TaskCount--;
                }
                Intent i = new Intent(ACTION_ON_GET_IMAGE);
                ImageBox.mQ.offer(b);
                sendBroadcast(i);
                if(TaskCount<=0)stopSelf();
            }
        });
    }

My BroadcastReceiver

我BroadcastReceiver

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            LOG.d(TAG, "BroadcastReceiver get broadcast");

            String action = intent.getAction();
            if (DownLoadImageService.ACTION_ON_GET_IMAGE.equals(action)) {
                Bitmap b = ImageBox.mQ.poll();
                if(b==null)return;
                if(mListener!=null)mListener.OnGetImage(b);
            }
        }
    };

#6


0  

It might be late but can help. On the first fragment or activity do declare a class...for example

可能会晚些,但会有所帮助。在第一个片段或活动中,请声明一个类……例如

   @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        description des = new description();

        if (requestCode == PICK_IMAGE_REQUEST && data != null && data.getData() != null) {
            filePath = data.getData();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);
                imageView.setImageBitmap(bitmap);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                constan.photoMap = bitmap;
            } catch (IOException e) {
                e.printStackTrace();
            }
       }
    }

public static class constan {
    public static Bitmap photoMap = null;
    public static String namePass = null;
}

Then on the second class/fragment do this..

然后在第二类/片段中做这个。

Bitmap bm = postFragment.constan.photoMap;
final String itemName = postFragment.constan.namePass;

Hope it helps.

希望它可以帮助。

#7


0  

You can create a bitmap transfer. try this....

您可以创建位图传输。试试这个....

In the first class:

在第一节课:

1) Create:

1)创建:

private static Bitmap bitmap_transfer;

2) Create getter and setter

2)创建getter和setter

public static Bitmap getBitmap_transfer() {
    return bitmap_transfer;
}

public static void setBitmap_transfer(Bitmap bitmap_transfer_param) {
    bitmap_transfer = bitmap_transfer_param;
}

3) Set the image:

3)设置图片:

ImageView image = (ImageView) view.findViewById(R.id.image);
image.buildDrawingCache();
setBitmap_transfer(image.getDrawingCache());

Then, in the second class:

然后,在第二节课:

ImageView image2 = (ImageView) view.findViewById(R.id.img2);
imagem2.setImageDrawable(new BitmapDrawable(getResources(), classe1.getBitmap_transfer()));

#8


-2  

In my case, the way mentioned above didn't worked for me. Every time I put the bitmap in the intent, the 2nd activity didn't start. The same happened when I passed the bitmap as byte[].

就我而言,上面提到的方法对我不起作用。每次我把位图放在意图中,第二个活动就没有开始。当我以byte[]传递位图时,也发生了同样的情况。

I followed this link and it worked like a charme and very fast:

我沿着这个链接,它就像一个魔术,非常快:

package your.packagename

import android.graphics.Bitmap;

public class CommonResources { 
      public static Bitmap photoFinishBitmap = null;
}

in my 1st acitiviy:

在我acitiviy 1:

Constants.photoFinishBitmap = photoFinishBitmap;
Intent intent = new Intent(mContext, ImageViewerActivity.class);
startActivity(intent);

and here is the onCreate() of my 2nd Activity:

这是我的第二个活动onCreate()

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bitmap photo = Constants.photoFinishBitmap;
    if (photo != null) {
        mViewHolder.imageViewerImage.setImageDrawable(new BitmapDrawable(getResources(), photo));
    }
}