代码之家  ›  专栏  ›  技术社区  ›  Kosmo零

如何在图形上绘制图像,而不在外部边界添加额外像素?

  •  0
  • Kosmo零  · 技术社区  · 6 年前

    这个简单的代码给了我非常糟糕的结果。

                Image global_src_img = Image.FromFile(Application.StartupPath + "\\src.png");
                Image src_img = ((Bitmap)global_src_img).Clone(new Rectangle(160, 29, 8, 14), PixelFormat.Format32bppArgb);
                src_img.Save(Application.StartupPath + "\\src_clonned.png", ImageFormat.Png);
                Bitmap trg_bmp = new Bitmap(100, 100);
                Graphics gfx = Graphics.FromImage(trg_bmp);
                gfx.FillRectangle(new Pen(Color.FromArgb(255, 0, 0, 0)).Brush, 0, 0, trg_bmp.Width, trg_bmp.Height);
                gfx.DrawImageUnscaled(src_img, (trg_bmp.Width / 2) - (src_img.Width / 2), (trg_bmp.Height / 2) - (src_img.Height / 2));
                gfx.Dispose();
                trg_bmp.Save(Application.StartupPath + "\\trg.png", ImageFormat.Png);
    

    它用字母复制大图像的一部分,并将其写入另一个图像。 在源图像和克隆图像中不存在的外部边界上,写入的图像具有额外的像素。 如何避免?

    这是克隆的图像( src_clonned.png )稍后将在图形上绘制。 enter image description here

    这是保存的结果图像( trg.png ) enter image description here

    1 回复  |  直到 6 年前
        1
  •  0
  •   Kosmo零    6 年前

    直接在位图上绘制,以避免对任何像素进行修改:

    public static void DrawImgOnImg(Image src, Bitmap trg, int x, int y)
    {
        for (int i = x; i < x + src.Width; i++)
            for (int j = y; j < y + src.Height; j++)
            {
                Color src_px = ((Bitmap)src).GetPixel(i - x, j - y);
                trg.SetPixel(i, j, src_px);
            }
    }