jimmyjambles
jimmyjambles

Reputation: 1670

Save bitmap pixel array as a new bitmap

I have a bitmap that I am performing a colorizing transformation on. I have the new array of pixels but I'm not sure how to then save them back to disk as an image

public static void TestProcessBitmap(string inputFile, string outputFile)
    {
        Bitmap bitmap = new Bitmap(inputFile);
        Bitmap formatted = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.PixelFormat.Format8bppIndexed);

        byte[] pixels = BitmapToPixelArray(formatted);

        pixels = Process8Bits(pixels, System.Windows.Media.Colors.Red);

        Bitmap output = new Bitmap(pixels); //something like this
    }

How can I then save the new pixels as a bitmap on disk?

Upvotes: 1

Views: 1396

Answers (2)

OnoSendai
OnoSendai

Reputation: 3970

I do believe you can use the Bitmap.Save() method after you have loaded the bytes back into a Bitmap object. This post may give you some insight on how to do it.

According to this MSDN document, if you only specify a path while using Bitmap.Save(),

If no encoder exists for the file format of the image, the Portable Network Graphics (PNG) encoder is used.

Upvotes: 2

Scott Gulliver
Scott Gulliver

Reputation: 71

You can convert a byte array to a bitmap using a MemoryStream, and then feeding it into the Image.FromStream method. Your example with this in place would be..

public static void TestProcessBitmap(string inputFile, string outputFile)
{
    Bitmap bitmap = new Bitmap(inputFile);
    Bitmap formatted = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.PixelFormat.Format8bppIndexed);

    byte[] pixels = BitmapToPixelArray(formatted);

    pixels = Process8Bits(pixels, System.Windows.Media.Colors.Red);

    using (MemoryStream ms = new MemoryStream(pixels))
    {
        Bitmap output = (Bitmap)Image.FromStream(ms);
    }
}

Upvotes: 1

Related Questions