Pasting Bitmaps into Text

In the (almost) old days, when you paste a bitmap into a rich-text editor, the editor would give it to OLE (Object Linking and Embedding) to figure out what to do with it. But these days, OLE isn’t always available, so it’s more general to paste them using the Windows Imaging Component (WIC) mentioned in the alpha-channel post and in the RichEdit 8.0 Image Support post. For example, you might want to paste an image from MS Paint or from the handy Snipping Tool. These programs offer bitmaps on the clipboard, although they don’t offer jpg’s or png’s. The bitmaps are in the memory-format Device Independent Bitmap (clipboard formats DIB and DIBV5). As such they are “raw” bitmaps without a bitmap file header. This is a problem for WIC since WIC only accepts bitmaps that have the correct bitmap file format as well as containing valid image data. Other image formats like png’s and jpg’s have headers identifying which codec to use, and WIC depends on this information.

Fortunately DIBs are easily converted to the bitmap file format by prepending the correct bitmap file header to the DIB data. WIC then happily accepts the result. As described in Device Independent Bitmap, a bitmap file header consists of fourteen bytes. You just have to choose the right ones! They are given in the following table

Byte IDs

Purpose

Value

0—1

Type

“BM” (little endian)

2—5

Size of file

Size of DIB + 14

6—7

Reserved

0

8—9

Reserved

0

10—13

Offset of image data

14 + size of DIB header

Here since “BM” is little endian, byte 0 is ‘B’ and byte 1 is ‘M’. The size of the DIB header is given by the first four bytes of the DIB. These bytes make up a little-endian 32-bit integer.

A different kind of bitmap file format is the ico format. The WIC documentation lists this format as one with a native WIC codec. The format provides for one or more icon bitmaps and later versions included png’s and alpha channels. The different bitmaps typically have different sizes, which is handy for accommodating various screen sizes and resolutions. Unfortunately, the native WIC codec can only decode ico files. For some reason, it cannot encode them, so if you paste one into your document, you can see it on screen but can’t save it. It’s tempting to write an ico codec that can encode as well as decode, but since nowadays it’s common to use regular images like png’s for icons, maybe a better ico codec doesn't have high priority.