Vladimirs
Vladimirs

Reputation: 970

PngBitmapEncoder not working as expected

I am trying to hide data in PNG images as follows:

        // Creates a new empty image with the pre-defined palette
        BitmapSource image = BitmapSource.Create(
            width,
            height,
            96,
            96,
            PixelFormats.Bgr24,
            myPalette,
            imageData,
            stride);

        PngBitmapEncoder encoder = new PngBitmapEncoder();
        encoder.Interlace = PngInterlaceOption.On;
        BitmapFrame frame = BitmapFrame.Create(image);
        encoder.Frames.Add(frame);

        //estimate PNG file size using the amount of data being saved
        MemoryStream arrayStream = new MemoryStream(imageData.Length);
        encoder.Save(arrayStream);

where imageData is the data that I am hiding in the PNG image. Here is how I decode it:

        Stream encodedImageStream = new MemoryStream(imageData, 0, imageDataSize);
        PngBitmapDecoder decoder = new PngBitmapDecoder(encodedImageStream, BitmapCreateOptions.None, BitmapCacheOption.Default);
        BitmapFrame bitmapSource = decoder.Frames[0];

        //align on the rhs boundary
        int stride = ((bitmapSource.PixelWidth + 1) * bytesPerPixel) & ~3;
        byte[] pixels = new byte[bitmapSource.PixelHeight * stride];
        bitmapSource.CopyPixels(pixels, stride, 0);

The problem is the encoder seems to be changing the PixelFormat of the image from Bgr24 to Bgr32, after decoding an image all of whose pixel values were set to 0 before encoding I get an image with pixel values - [0,0,0,255,0,0,0,255,...] which suggests that the encoder added transparency to the image, I would like it to keep the format the same, please help

Upvotes: 0

Views: 1595

Answers (1)

totowtwo
totowtwo

Reputation: 2147

Try encoder.Palette = BitmapPalettes.Gray256;

Upvotes: 1

Related Questions