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

如何在内存中创建指定宽高和颜色的System.Drawing.Image对象?

在内存中创建指定尺寸和颜色的Image对象

可以通过GDI+的相关类直接在内存中生成目标图像,完全不需要涉及物理文件操作,具体实现方案如下:

实现代码

using System.Drawing;
using System.Drawing.Imaging;

public static class ImageCreator
{
    public static Image Image(int width, int height, Color color)
    {
        // 创建内存中的Bitmap对象(Bitmap是Image的子类,可直接返回)
        var bitmap = new Bitmap(width, height);
        
        // 借助Graphics对象填充纯色背景
        using (var graphics = Graphics.FromImage(bitmap))
        {
            graphics.Clear(color);
        }
        
        return bitmap;
    }
}

核心说明

  • 直接使用Bitmap类在内存中创建图像容器,它继承自Image,完全满足方法的返回类型要求
  • 通过Graphics.Clear()方法一次性填充整个画布为指定颜色,操作高效且逻辑简单
  • 用using语句管理Graphics对象,确保绘图资源被及时释放,避免内存泄漏
  • 整个流程全程在内存中完成,不会生成任何物理文件

内容的提问来源于stack exchange,提问作者William Jockusch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 23:15:52