Export (0) Print
Expand All

How to: Encode and Decode a BMP Image

The following examples show how to decode and encode a bitmap (BMP) image using the specific BmpBitmapDecoder and BmpBitmapEncoder objects.

This example demonstrates how to decode a BMP image using a BmpBitmapDecoder from a Uri.


// Open a Uri and decode a BMP image
System::Uri^ myUri = gcnew System::Uri("tulipfarm.bmp", UriKind::RelativeOrAbsolute);
BmpBitmapDecoder^ decoder2 = gcnew BmpBitmapDecoder(myUri, BitmapCreateOptions::PreservePixelFormat, BitmapCacheOption::Default);
BitmapSource^ bitmapSource2 = decoder2->Frames[0];

// Draw the Image
Image^ myImage2 = gcnew Image();
myImage2->Source = bitmapSource2;
myImage2->Stretch = Stretch::None;
myImage2->Margin = System::Windows::Thickness(20);

This example demonstrates how to encode a BitmapSource into a BMP image using a BmpBitmapEncoder.

            int width = 128;
            int height = width;
            int stride = width / 8;
            array<System::Byte>^ pixels = gcnew array<System::Byte>(height * stride);

			List<Color>^ colors = gcnew List<Color>();
            colors->Add(Colors::Red);
            colors->Add(Colors::Blue);
            colors->Add(Colors::Green);
            BitmapPalette^ myPalette = gcnew BitmapPalette(colors);

			// Creates a new empty image with the pre-defined palette

               BitmapSource^ image = BitmapSource::Create(
                  width,
                  height,
                  96,
                  96,
                  PixelFormats::Indexed1,
                  myPalette,
                  pixels,
                  stride);

               FileStream^ stream = gcnew FileStream("new.bmp", FileMode::Create);
               BmpBitmapEncoder^ encoder = gcnew BmpBitmapEncoder();
               TextBlock^ myTextBlock = gcnew TextBlock();
               myTextBlock->Text = "Codec Author is: " + encoder->CodecInfo->Author->ToString();
               encoder->Frames->Add(BitmapFrame::Create(image));
               encoder->Save(stream);
Show:
© 2014 Microsoft