最近有人问道如何在两个activity跳转的过程中携带Bitmap跳转过去,在网上找了很多这样的解答,但是绝大多部分并没有达到我想要的结果,因此我将我实现的几行代码与大家一起分享。
这个是第一个Activity中的代码
/*
我们在这里是要将bitmap的数据转化成byte数组 使用intent传递到第二个Activity中去
*/
public class MainActivity extends AppCompatActivity {
private Button button ;
byte[] result; //将bitmap转化的byte数组
Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
//模拟加载的一个数据
bitmap =BitmapFactory.decodeResource(getResources(),R.drawable.demo);
ByteArrayOutputStream output = new ByteArrayOutputStream();//初始化一个流对象
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);//把bitmap100%高质量压缩 到 output对象里
result = output.toByteArray();//转换成功了 result就是一个bit的资源数组
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
//使用byte数组传递数据
intent.putExtra("bitmap",result);
startActivity(intent);
}
});
}
}
—————————————————-
这个是第二个Activity中的代码,跳转后接收数据
public class Main2Activity extends AppCompatActivity {
byte[] res; //接收传递过来的byte数组
Bitmap mImageIds ; //转换后的bitmap
private ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
image = (ImageView) findViewById(R.id.image);
//下面这句表示在intent中拿到bitmap对应的数组
res = getIntent().getByteArrayExtra("bitmap");
image.setImageBitmap(getPicFromBytes(res,null));
}
//下面的这个方法是将byte数组转化为Bitmap对象的一个方法
public static Bitmap getPicFromBytes(byte[] bytes, BitmapFactory.Options opts) {
if (bytes != null)
if (opts != null)
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
else
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
return null;
}
}
关于BitmapFactory.Options opts的简单理解,因为我们上面无需这个类,我就设置为null了
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;// 如果值设为true,那么将不返回实际的bitmap,也不给其分配内存空间,这样就避免了内存溢出。
正规的说明是这样的:
如果值设为true,那么将不返回实际的bitmap,也不给其分配内存空间,这样就避免了内存溢出。但是允许我们查询图片的信息,这其中就包括图片的大小信息(options.outHeight(图片的原始高度)和options.outWidth(图片的原始宽度))。
inSampleSize==2,则取出的缩略图的宽和高都是原始图片的1/2,图片的大小就是原始图片的1/4。