Using gdi+ to save bitmaps as png's
Posted: Wed Aug 08, 2007 12:38 pm
Hi,
I'm trying to get gdi+ to save a 32-bit bitmap with an alpha channel to 32-bit png format.
Saving as png is no problem, preserving the alpha channel on the other hand...
It seems that 'basic' gdi+ will not recognise the alpha channel in a 32-bit bitmap, which kind of makes sense, after all bitmaps are not really supposed to have alpha transparency. I suspect that I need to use image attributes, but with so little available documentation on gdi+ I'm a little stuck.
Anyone know how I should proceed?
I have some code. The following creates a normal 32-bit gdi bitmap, shoves a white box in the middle of it. Converts it to a gdi+ bitmap, sets all black pixels to have full transparency and uses gdi+ to save it in png format.
You'll need SFSxOI's gdi wrappers and Freak's macro framework to run the code : http://www.purebasic.fr/english/viewtopic.php?t=26459
Whilst the code creates a 32-bit png (as opposed to PB's 24-bit png) you'll see that the saved png has reset all of the alpha values to 255 (fully opaque!) You can see the lack of transparency by simply loading the resulting png in MS image viewer.
Any help much appreciated.
I'm trying to get gdi+ to save a 32-bit bitmap with an alpha channel to 32-bit png format.
Saving as png is no problem, preserving the alpha channel on the other hand...

Anyone know how I should proceed?
I have some code. The following creates a normal 32-bit gdi bitmap, shoves a white box in the middle of it. Converts it to a gdi+ bitmap, sets all black pixels to have full transparency and uses gdi+ to save it in png format.
You'll need SFSxOI's gdi wrappers and Freak's macro framework to run the code : http://www.purebasic.fr/english/viewtopic.php?t=26459
Code: Select all
XIncludeFile "gdiplus_11.pbi"
*token = Gdiplus_New()
If *token
;Let's create our 'main' image.
mainImage = CreateImage(#PB_Any, 300, 300, 32)
;Only proceed if the image creation succeeded.
If mainImage
hdc = StartDrawing(ImageOutput(mainImage))
;Chuck a white box in the middle.
Box(40,40,220,220,#White)
;Now steam into gdi+ and attempt to convert to png with alpha channel.
If GdipCreateFromHDC(hdc, @*graphics) = #Ok
;Create a gdi+ bitmap based on our gdi one.
GdipCreateBitmapFromHBITMAP(ImageID(mainImage), 0, @*image)
;Set the alpha values of all 'black' pixels.
For row = 0 To ImageHeight(mainImage)-1
For col = 0 To ImageWidth(mainImage) - 1
GetPixel(*image, col, row, @color)
;If color is black then set to transparent.
If color&$ffffff = 0
color=0
SetPixel(*image, col, row, color)
EndIf
Next
Next
Gdiplus_ImageSaveToFile(*image, "test.png", #Png_Encoder)
GdipDisposeImage(*imgage)
EndIf
StopDrawing()
FreeImage(mainImage)
GdipDeleteGraphics(*graphics)
EndIf
EndIf
Gdiplus_Del(*token)
End
Any help much appreciated.