Why does GDI + disable scaled images?

I am doing some image scaling using GDI + (C #) and noticed a problem when the image that I am scaling is cropped along the left and top edges.

http://zctut.com/cutoff.png

To reproduce this, create a new form project, save this image in the bin \ debug folder and add the following code to the form (and, accordingly, events):

public partial class Form1 : Form { public Form1() { InitializeComponent(); } int scale = 1; Image img = Image.FromFile("circle.png"); private void Form1_Paint(object sender, PaintEventArgs e) { //this makes the glitch easier to see e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; RectangleF srcRect = new RectangleF(0f, 0f, img.Width, img.Height); RectangleF destRect = new RectangleF(0f, 0f, img.Width * scale, img.Height * scale); e.Graphics.DrawImage(img, destRect, srcRect, GraphicsUnit.Pixel); } private void Form1_Click(object sender, EventArgs e) { scale++; if (scale > 8) scale = 1; Invalidate(); } } 

As you can see, the left and top rows of pixels are cropped as if the zoom rectangle started halfway in the pixel.

Edit: for the note, I also tried using scale transformation instead of using rectangles as above, and it got exactly the same.

Now, having said that, I have found a job. If you change the rectangle declarations in the example above, follow these steps:

 RectangleF srcRect = new RectangleF(-0.5f, -0.5f, img.Width, img.Height); 

So that we correct the "half", the image is displayed correctly.

Basically, although this is easy to get around, am I doing something wrong or is this normal behavior?

Edit: as suggested by Andrei Pana, I tried to add this code before calling the drawing:

 e.Graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None; 

And, unfortunately, this did not affect the rendering. The edge was still cut off.

+8
c # gdi + image-manipulation
source share
3 answers

Try setting PixelOffsetMode to PixelOffsetMode.Half. By default, for high-speed anti-aliasing, pixels are offset by -0.5

+12
source share

Set the image size 2 pixels larger (in each dimension) than on the graph it contains. I also ran into this, and found that overshot smoothing never exceeds 1 pixel on each side.

In other words, either turn off anti-aliasing (which will fix this), or change this section of your code:

 RectangleF destRect = new RectangleF(0f, 0f, img.Width * scale, img.Height * scale); 

:

 RectangleF destRect = new RectangleF(1f, 1f, img.Width * scale -2, img.Height * scale -2); 

(or use an equivalent job that uses srcRect)

Yes, this is normal behavior and is a known issue with GDI + /. Net.

0
source share
0
source share

Source: https://habr.com/ru/post/650283/


All Articles