I am trying to write a file from Clipboard if it contains image. As clipboard can contain Image of any depth (8/16/24/32 bit) or it can contain alpha channel as well.
What i am doing is, first check for data object. If it has a data object then i check for DataFormat
if it is Dib
, get the Dib Stream
and convert it to System.Drawing.Bitmap
for conversion i took a code from here.
if (Clipboard.GetDataObject() == null)
return null;
if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Dib))
{
MemoryStream dibStream = Clipboard.GetData(DataFormats.Dib) as MemoryStream;
Bitmap img = DIBitmaps.DIB.BitmapFromDIB(dib); //taken from link provided
img.Save(@"output.png",ImageFormat.Png);
}
For input image, I am using Adobe Photoshop
and Microsoft Power Point
to copy image to clipboard. The thing i came to realize that Microsoft Power Point
image is 32 bit
and Photoshop
is 24 bit
. But thats not an issue as BitmapFromDIB()
takes care of that.
Everything is working fine except the transparency. If an image is transparent then BitmapFromDIB
does not respect that. It ignores the Alpha
channel. For 32 bit
images i changed 32 bit
handling of PixelFormat
, and changed
fmt = PixelFormat.Format32bppRgb;
to
fmt = PixelFormat.Format32bppArgb;
But thats not an ideal solution as even if original Dib Stream does not have an alpha channel it will add to it. So this was the first part of problem one.
The second part is for 24 bit
Images as there is not any PixelFromat
available that has 24 bit with Alpha. So the result is following.
As you can see on the left image is transparent from center but not in the result.
The other issue i am having is images from Power Point
which are 32 bit
Some how they are shifted around 4-5 pixels to the right and text is not smooth either, which is probably a Aliasing thing. But the brighter side is transparent area is transparent in 32 bit images.
How can i handle transparency while converting from DIB to Bitmap?
Why images are shifted right in 32 bit
images?
Any help would be really appreciated.
I can answer the last issue, on the shifted image.
DIB has multiple formats, specified by the "Compression" option in the header. This isn't limited to actual compression formats, but contains various formats differing from the standard, so it should always be checked before processing the data. If the format is using compression type 3 (BI_BITFIELDS
) instead of 0 (BI_RGB
), then the image data starts with three Int32 bit masks that specify which bits to read to get the R, G and B components of a 32-bit pixel. Generally, those are set to the default expected values (0x00FF0000 for R, 0x0000FF00 for G and 0x000000FF for B), so if they are, you don't really need to do anything special with the data itself, but either way, you still need to skip these twelve bytes, of course, or they'll show up as three pixels on your image.
So clearly, your DIB methods are lacking. I wrote my own; you can check them out in this answer: