Android传递Bitmap的两种简单方式及其缺陷

Android传递Bitmap的几种简单方式

一,通过Intent的Bundle。
比如有两个activity,A,B,从A进入B。先在A中将Bitmap写进去:

Resources res=getResources();
		Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.ic_launcher);
		
		Bundle b = new Bundle();
        b.putParcelable("bitmap", bmp);
        
        Intent intent = new Intent(this, MainActivity2.class);
        intent.putExtras(b);
        startActivity(intent);

然后在B中解析、接收Bitmap:

Intent intent=getIntent();
		Bundle b=intent.getExtras();
		Bitmap bmp=(Bitmap) b.getParcelable("bitmap");

此种传递方式的缺陷:只能传递相对较小适中大小的Bitmap,如果Bitmap大小尺寸过大就会引起代码崩溃。


二,把Bitmap写进字节流。
比如有两个activity,A,B,从A进入B。先在A中将Bitmap写进字节流传递出去:

Resources res=getResources();
		Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.ic_launcher);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] bytes=baos.toByteArray();
        
        Bundle b = new Bundle();
        b.putByteArray("bitmap", bytes);
        
        Intent intent = new Intent(this, MainActivity2.class);
        intent.putExtras(b);
        startActivity(intent);

然后在B中接收Bitmap的字节流并恢复出来:

Intent intent=getIntent();
		Bundle b=intent.getExtras();
		byte[] bytes=b.getByteArray("bitmap");
		
		Bitmap bmp=BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

此种传递方式的缺陷:缺陷同第一种方式相同。


小结:

以上两种方式均适用于适中、较小图片,如果图片过大如MB量级的,就不能正常工作了。


原文地址:https://www.cnblogs.com/hehehaha/p/6147308.html