0

Is it possible to convert a indexed Bitmap to a unindexed without losing any quality?

I currently use this code to convert:

public Bitmap CreateNonIndexedImage(Image src)
        {
            Bitmap newBmp = new Bitmap(src.Width, src.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            using (Graphics gfx = Graphics.FromImage(newBmp))
            {
                gfx.DrawImage(src, 0, 0);
            }

            return newBmp;
        }

Here is the indexed bitmap: http://puu.sh/6VO1N.png

And this is the converted image: http://puu.sh/6VO2Q.png

I need the unindexed to be exactly the same as the indexed but I don´t know what to do.

Hobbit9797
  • 35
  • 7
  • Maybe you should set `SmoothingMode` to None. – L.B Feb 14 '14 at 14:47
  • This doesn´t work. @L.B – Hobbit9797 Feb 14 '14 at 14:57
  • 1
    If anyone sees this later... this is due to DPI. Giving a rectangle with the original width and height to `DrawImage` instead of just coordinates fixes this, since the 'scaling' given by the rectangle will override the DPI scaling. – Nyerguds Mar 08 '18 at 19:36

1 Answers1

1

The image was resampled. That's normally a Good Thing, it helps to get rid of the dithering artifacts in the original image. But you don't like it so you have to turn interpolation off. You also should use the DrawImage() overload that prevents rescaling due to the resolution of the original image. Not actually a problem with the image you've got but it could be one with another. Thus:

    public static Bitmap CreateNonIndexedImage(Image src) {
        Bitmap newBmp = new Bitmap(src.Width, src.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

        using (Graphics gfx = Graphics.FromImage(newBmp)) {
            gfx.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None;
            gfx.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
            gfx.DrawImage(src, new Rectangle(0, 0, src.Width, src.Height));
        }

        return newBmp;
    }
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536