Search code examples
c#graphicssystem.drawing

InterpolationMode HighQualityBicubic introducing artefacts on edge of resized images


Using some pretty stock standard C# code to resize an image, and place it on a coloured background

Image imgToResize = Image.FromFile(@"Dejeuner.jpg");
Size size = new Size(768, 1024);
Bitmap b = new Bitmap(size.Width, size.Height);

Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.Green, 0, 0, size.Width, size.Height);

g.DrawImage(imgToResize, new Rectangle(0,150,768, 570));
b.Save("sized_HighQualityBicubic.jpg");

The result has a funny artefact in the 0th and 1st columns of pixels. The 0th column appears to be mixed with the background colour, and the 1st column has been made lighter.

See the top left corner zoomed for high quality bicubic and bicubic.

HighQualityBicubic

Bicubic

..and HighQualityBilinear

HighQualityBilinear

This forum post appears to be someone with the same problem: DrawImage with sharp edges

The sounds like a bug to me? I can understand why the colours would mix at the top of the resized image. But mixing the colours on the left / right edges doesn't make sense. Does anyone know of a fix to prevent these artefacts?

Update: very similar conversation going on in the comments here: GDI+ InterpolationMode


Solution

  • Shamelessly lifting the answer from this question, I found this fixes it:

    using (ImageAttributes wrapMode = new ImageAttributes())
    {
        wrapMode.SetWrapMode(WrapMode.TileFlipXY);
        g.DrawImage(input, rect, 0, 0, input.Width, input.Height, GraphicsUnit.Pixel, wrapMode);
    }