Bitmap对象封装了GDI+中的一个位图,此位图由图形图像及其属性的像素数据组成.因此Bitmap是用于处理由像素数据定义的图像的对象。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace bmpdemo
{
    
    public partial class Form1 : Form
    {
        Bitmap bmp1;
        Rectangle rect1;
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            bmp1 = new Bitmap(100, 100);
            Graphics g = Graphics.FromImage(bmp1);
            g.DrawString("bmp测试,", this.Font, Brushes.Black, 20, 20);
            rect1 = new Rectangle(30, 40, 40, 40);
            g.FillRectangle(Brushes.Green, rect1);
            g.Dispose();
            for(int i=60; i<90;i++)
            {
                bmp1.SetPixel(i, 70, Color.Red);
            }            
            pictureBox1.Image = bmp1;
            textBox1.Text = Image.GetPixelFormatSize(bmp1.PixelFormat).ToString();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            bmp1.Save("E:\\bmpdemo.jpg");
        }
    }
} 
先生成一个100*100大小的位图bmp1;
然后从bmp1获取Graphics对象g,然后用g进行绘制,这样绘制的东西是绘制在bmp1上;绘制字符串,绘制矩形;
然后调用bmp1对象的SetPixel方法,设置一些像素点的颜色;
然后把bmp1赋值给pictureBox的Image属性,这会在pictureBox中显示bmp1;
然后返回一下bmp1对象的颜色深度;
位图的颜色深度的含义是,
若色彩深度是n位,即有2^n种颜色选择,而储存每像素所用的位数就是n;
bmp1的颜色深度是32;如果颜色深度是8,可以表示2^8=256种颜色;
保存图片,可以调用bmp1的Save方法,或者
pictureBox1.Image.Save("E:\\bmpdemo222.jpg");
调用pictureBox控件的Image属性的Save方法;
运行和打开保存的图片如下,




















