首页 > 解决方案 > 位图马赛克

问题描述

        Bitmap source = (Bitmap)Bitmap.FromFile(@"lena_std.tif");
        Bitmap dest = new Bitmap(source.Width * 3, source.Height * 3, source.PixelFormat);

        for (int y = 0; y < source.Height; y++)
        {
            for (int x = 0; x < source.Width; x++)
            {
                Color clr = source.GetPixel(x, y);
                dest.SetPixel(x, y, clr);

                dest.SetPixel(x, y * 2, clr);
                dest.SetPixel(x * 2, y, clr);
                dest.SetPixel(x * 2, y * 2, clr);

                dest.SetPixel(x * 3, y, clr);
                dest.SetPixel(x, y * 3, clr);
                dest.SetPixel(x * 3, y * 3, clr);
            }
        }

        pictureBox1.Image = dest;

我希望获得如下的莉娜马赛克:

在此处输入图像描述

但是,得到了一个扭曲的图像:

在此处输入图像描述

什么地方出了错?

标签: c#bitmap

解决方案


您得到的正是您所要求的:) 例如,对于 x 和 y 为 0,您将像素设置为 (0,0) 七次(而不是九次)。您需要偏移图像的宽度和高度。

对于 3x3 马赛克,将 SetPixel 语句替换为

for (j=0; j<3; j++)
  for (i=0; i<3; i++)
     dest.SetPixel(i*source.Width+x, j*source.Height+y, clr);

总而言之:

for (y = 0; y < source.Height; y++)
    for (x = 0; x < source.Width; x++)
    {
        Color clr = source.GetPixel(x, y);
        for (j=0; j<3; j++)
           for (i=0; i<3; i++)
              dest.SetPixel(i*source.Width+x, j*source.Height+y, clr);    
    }

推荐阅读