You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发:如何通过构造方法传递Bitmap对象?

如何在MainActivity中实例化Item对象?

先看你给出的代码片段:

public class Item {
    private Bitmap image;
    public Item(Bitmap image) {
        this.image = image;
    }
}
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 疑问在此行
        Item item = new Item(???);
    }
}

问题的核心是获取一个有效的Bitmap对象传入Item的构造方法,下面是Android开发中几种常用的获取Bitmap的方式,你可以根据实际需求选择:


1. 从应用内置资源文件(drawable/mipmap)获取

这是最常用的场景,比如你把图片放在res/drawable或res/mipmap目录下:

// 直接读取drawable中的图片,替换R.drawable.my_image为你的资源ID
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
Item item = new Item(bitmap);

如果担心图片太大占用内存,可以用BitmapFactory.Options做内存优化:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2; // 将图片缩小为原图的1/2,降低内存占用
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image, options);
Item item = new Item(bitmap);

2. 从本地存储文件获取

如果图片在手机本地文件系统中(比如SD卡),需要先确保已申请READ_EXTERNAL_STORAGE权限(Android 6.0及以上需动态申请),再用以下代码:

String filePath = "/sdcard/Pictures/my_photo.jpg"; // 替换为你的实际文件路径
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
if (bitmap != null) {
    Item item = new Item(bitmap);
} else {
    // 处理文件不存在或解码失败的情况
}

3. 从网络加载Bitmap

从网络加载图片不能直接在主线程执行,推荐用第三方库(比如Glide)简化操作,先在build.gradle中添加依赖后,可这样实现:

Glide.with(this)
     .asBitmap()
     .load("https://example.com/remote_image.jpg") // 替换为你的图片URL
     .into(new CustomTarget<Bitmap>() {
         @Override
         public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
             // 图片加载完成后实例化Item
             Item item = new Item(resource);
             // 后续业务逻辑
         }

         @Override
         public void onLoadCleared(@Nullable Drawable placeholder) {
             // 清理临时资源
         }
     });

4. 从界面View生成Bitmap

如果需要把某个View转换成Bitmap(比如截图):

View targetView = findViewById(R.id.target_view); // 替换为你的View ID
targetView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(targetView.getDrawingCache());
targetView.setDrawingCacheEnabled(false); // 关闭缓存避免内存泄漏
Item item = new Item(bitmap);

小贴士:Bitmap是高内存占用对象,使用完毕后记得调用bitmap.recycle()释放内存,避免出现OOM(内存溢出)问题!

内容的提问来源于stack exchange,提问作者mr L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:37:54