简体   繁体   中英

How to draw image on Graphics without extra pixels at outer borders?

This simple code gives me very bad result.

            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);

It clones part of the big image with letters and writes it to another image. Written image has extra pixels at outer borders that does not present in source image same as in cloned image. How to avoid it?

This is cloned image ( src_clonned.png ) that later will be drawn on graphics. 在此处输入图片说明

This is saved resulting image ( trg.png ). 在此处输入图片说明

Draw directly on bitmap to avoid any pixels modifications with this:

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);
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM