W
e
l
c
o
m
e
: )

Android通过Intent传图片

一、背景

在使用listView列表时,将图片文本存在列表中,点击列表或修改按钮时跳转到另一个活动页面显示图片。这时就需要取出图片,问题就此而来了。

二、遇到的问题

取出图片,直接对ImageView设置图片背景,不能显示。

三、解决方法

方式一(推荐):
取值:

private String[] context = {"乒乓球", "羽毛球", "网球"};
private int[] imageViews = {R.drawable.abd, R.drawable.abcd, R.drawable.absss};
private List<HashMap<String, Object>>   list = new ArrayList<>();

Intent intent = new Intent(MainActivity2.this, MainActivity3.class);
HashMap<String, Object> stringObjectHashMap = list.get(position);
ImageView imageView = view.findViewById(R.id.imageView);
//  R.drawable.add ==> stringObjectHashMap.get("image").toString()
intent.putExtra("image", stringObjectHashMap.get("image").toString());
startActivity(intent);

取值:

String photo = getIntent().getStringExtra("image").toString();
Resources resources = this.getResources();
Drawable drawable = resources.getDrawable((int) Long.parseLong(photo));
imageView.setImageDrawable(drawable);

方式二:
注意:这种方式对API有要求,
存值

 private String[] context = {"乒乓球", "羽毛球", "网球"};
 private int[] imageViews = {R.drawable.abd, R.drawable.abcd, R.drawable.absss};
 private Bitmap bitmap;
    byte buff[] = new byte[125*250];

Intent intent = new Intent(MainActivity2.this, MainActivity3.class);
HashMap<String, Object> stringObjectHashMap = list.get(position);
bitmap = BitmapFactory.decodeResource(getResources(), (Integer) stringObjectHashMap.get("image"));
 buff = Bitmap2Bytes(bitmap);
 intent.putExtra("image", buff);
 startActivity(intent);

//放在外面
private byte[] Bitmap2Bytes(Bitmap bm){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

取值:

Intent mIntent = getIntent();
byte buff[]=mIntent.getByteArrayExtra("image");
Bitmap  bitmap = BitmapFactory.decodeByteArray(buff, 0, buff.length);
BitmapDrawable mBitmapDrawable = new BitmapDrawable(bitmap);
//API16要求
imageView.setBackgroundDrawable(mBitmapDrawable);

如:
在这里插入图片描述
方式二不推荐。

posted @ 2022-11-25 22:26  所遇所思  阅读(47)  评论(0)    收藏  举报  来源