Search code examples
c#system.drawing

Blit pixels from one image to bitmap without scaling


I am creating an image from file by using

var img = Image.FromFile(openFileDialog1.FileName);

I also create a Bitmap with the same size

var bmp = new Bitmap(img.Width, img.Height);

var g = Graphics.FromImage(bmp);

then I draw from the image to the bitmap using

var r = new Rectangle(tileoffsetx, tileoffsety, tilewidth, tileheight);

g.DrawImage(img, destx, desty, r, GraphicsUnit.Pixel);

I have also tried

var r = new Rectangle(tileoffsetx, tileoffsety, tilewidth, tileheight);

g.SetClip(r);

g.DrawImageUnscaled(img, destx, desty);

In both cases, I have get unexpected scaling. (Even when I am using the DrawImageUnscaled version).

In both cases, I get a result that is around 1/3 the size of the original.

That seems to correspond with the fact that the image has a resolution of 300 pixels/inch and the bitmap a resolution of 96 pixels/inch.

How do I copy pixels regardless of pixels / inch?


Solution

  • I tried an idea from the comments, using the form of drawImage that takes 2 rects. It goes like

    var srcrect = new Rectangle(tileoffsetx, tileoffsety, tilewidth, tileheight);
    var destrect = new Rectangle(destx, desty, tilewidth, tileheight);
    
    g.DrawImage(img, destrect, srcrect, GraphicsUnit.Pixel);
    

    and that succeeded!