Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is GDI+ cutting off scaled images?

I am doing some image scaling using GDI+ (C#), and have noticed a problem where the image I am scaling is being cut off along the left and top edges.

http://zctut.com/cutoff.png

To reproduce this, create a new form project, save this image into the bin\debug folder, and add the following code to the form (and, the corresponding 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-most rows of pixels are being cut off, as if the scaling rectangle is starting half-way in the pixel.

Edit: For note, I also tried using a Scale transform instead of using rectangles as above, and it rendered exactly the same.

Now, that said, I did discover a work around. If you change the rectangle declarations in sample above like this:

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

So that we correct for the "half-way" thing, then the image renders correctly.

Basically, while this is easy to work around, am I doing something wrong, or is this normal behaviour?

Edit: As per Andrei Pana's suggestion, I tried adding this code before the drawing call:

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

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

like image 639
Mike Caron Avatar asked Dec 19 '10 06:12

Mike Caron


1 Answers

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

like image 96
Andrei Pana Avatar answered Dec 02 '22 21:12

Andrei Pana