Question

I have an image that is saved as a size of 64x64 on disk. I load the image using this code:

resizeImage(Image.FromFile(@"C:\Users\ApachePilotMPE\Desktop\" + "img.png"), new Size(128, 128))

which returns a bitmap cast as an image like so:

public static Image resizeImage(Image i, Size newSize)
{
    return (Image)(new Bitmap(i, newSize));
}

When I paint that image on the form, the sides of the object in the image (just a black & white stick figure, with a transparent background) appear as if they have been antialiased to blend with the background. Is there any way to keep this from happening? I have tried setting the Graphics.SmoothingMode to None at runtime, but that doesn't seem to have any effect.

enter image description here

Top: Painted Image when loaded in with size 64 and increased to 128.

Bottom Left: Painted Image when loaded at 128.

Bottom Right: Edited-In Image, resized with Paint.NET, size 128.

To specify: The top image SHOULD look like the bottom left.

EDIT

Check updated code at the top of the post.

Was it helpful?

Solution

  return (Image)(new Bitmap(i, newSize));

You are letting the Bitmap constructor resize the image. It will pick a "good" interpolation mode that attempts to avoid the blocky appearance you get from making pixels four times as big. You however prefer the blocky look, that means you'll have to take control of the Interpolation mode yourself. Like this:

    public static Image ResizeImage(Image img, Size size) {
        var bmp = new Bitmap(size.Width, size.Height);
        using (var gr = Graphics.FromImage(bmp)) {
            gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
            gr.DrawImage(img, new Rectangle(Point.Empty, size));
        }
        return bmp;
    }

Also note that you may prefer the look you'll get when you insert gr.Clear(Color.White); inside that code and not change the InterpolationMode. That avoids a problem with the transparent pixels in the original image having an awkward RGB value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top