如何绘制一张图片?

3

我如何使用图形绘制创建一个256x256的色彩空间图像?目前我正在使用指针循环遍历每个像素位置并对其进行设置。蓝色从X轴的0到255,绿色从Y轴的0到255.如下所示初始化图像。

Bitmap image = new Bitmap(256, 256);
imageData = image.LockBits(new Rectangle(0, 0, 256, 256),
            ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
for (int row = 0; row < 256; row++)
{
    byte* ptr = (byte*)imageData.Scan0 + (row * 768);
    for (int col = 0; col < 256; col++)
    {
         ptr[col * 3] = (byte)col;
         ptr[col * 3 + 1] = (byte)(255 - row);
         ptr[col * 3 + 2] = 0;
    }
}

我有一个滑块,它在红色上的取值范围是0...255。每次拖动滑块,它都会进入下面的循环并更新图片。

for (int row = 0; row < 256; row++)
{
    byte* ptr = (byte*)imageData.Scan0 + (row * 768);
    for (int col = 0; col < 256; col++)
    {
         ptr[col * 3 + 2] = (byte)trackBar1.Value;
    }
}

我已经找到了使用ColorMatrix来滚动部分的方法,但是如何在不使用指针或SetPixel的情况下初始化图像呢?


我使用指针是因为它是最容易理解和使用的方法,我可以直接通过循环来更新值。而且它比使用GetPixel和SetPixel的替代方法更快速。 - Jack
3个回答

3

首先,在表单中添加PictureBox控件。

接下来,此代码将根据循环中的索引为每个像素分配不同的颜色,并将图像分配给该控件:

Bitmap image = new Bitmap(pictureBox3.Width, pictureBox3.Height);
SolidBrush brush = new SolidBrush(Color.Empty);
using (Graphics g = Graphics.FromImage(image))
{
    for (int x = 0; x < image.Width; x++)
    {
        for (int y = 0; y < image.Height; y++)
        {
            brush.Color = Color.FromArgb(x, y, 0);
            g.FillRectangle(brush, x, y, 1, 1);
        }
    }
}
pictureBox3.Image = image;

由于某些原因,我没有找到像我预期的SetPixelDrawPixel这样的函数,但是当你给参数1×1时,FillRectangle可以完成完全相同的操作。

请注意,对于小图像它可以正常工作,但图像越大,速度就会越慢。


1
嗯,OP提到出于性能原因不想使用SetPixel,我认为绘制一个1x1的矩形也不会更好。 - gordy
@Gordy 对于256x256的图像,这仍然很好,并且大约需要一秒钟-由于OP接受了答案,我想他在效率方面做出了妥协。请注意,我不会每次都创建新的“Brush”,以避免混乱内存。 - Shadow The Spring Wizard

1

如果你不想使用指针或SetPixel,那么你就必须在一个字节数组中构建渐变,然后使用Marshal.Copy将其复制到位图上:

int[] b = new int[256*256];
for (int i = 0; i < 256; i++)
    for (int j = 0; j < 256; j++)
        b[i * 256 + j] = j|i << 8;

Bitmap bmp = new Bitmap(256, 256, PixelFormat.Format32bppRgb);
BitmapData bits = bmp.LockBits(new Rectangle(0, 0, 256, 256),
    ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);

Marshal.Copy(b, 0, bits.Scan0, b.Length);

0
这将为您创建一个256x256的白色图像。
Bitmap image = new Bitmap(256, 256);
using (Graphics g = Graphics.FromImage(image)){
    g.FillRectangle(Brushes.White, 0, 0, 256, 256);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接