Intent传递Bitmap
最近有人问道如何在两个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。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)