Save pic with transparency

Hi guys!
I’m trying to save a pic with transparency.

This is my code… it’s in paint event of canvas. The canvas can show the photo with transparency, but when saved to a file, it lost the transparency.

if doPaint = True then
dim newPic as new Picture(originalPic.width, originalPic.height, 32)
newPic.Graphics.DrawPicture(originalPic, 0, 0, originalPic.width, originalPic.height)
newPic.Transparent = 1

Dim surf As RGBSurface = newPic.RGBSurface
Dim surfOriginal As RGBSurface = newPic.RGBSurface
Dim lastX As Integer = originalPic.Width - 1
Dim lastY As Integer = originalPic.Height - 1

For y As Integer = 0 To lastY
For x As Integer = 0 To lastX
If surf.Pixel(x, y).red < 200 and surf.Pixel(x, y).green < 200 and surf.Pixel(x, y).blue < 200 Then
surf.Pixel(x, y) = surfOriginal.Pixel(x, y)
end if
Next
Next

newPic.Save(saveFoto, Picture.SaveAsPNG)

g.DrawPicture(newPic, 0, 0, originalPic.Width, originalPic.Height)
end if

Thanks!

You need to create a MASK layer

something like this… dont just cut/paste this… its just to provide an inspiration :slight_smile:

[code]
Dim f As FolderItem
Dim f2 As FolderItem
Dim s As String
Dim t As String
Dim p As picture
Dim ps As RGBSurface
Dim new_p As picture
Dim new_m As picture
Dim new_mg As graphics
Dim new_g As graphics
dim x as integer
dim y as integer
f=GetFolderItem("")

	p=picture.Open(f)
	
	new_p = New picture(p.width,p.height,32)
	new_g=new_p.graphics
	new_g.drawpicture p,0,0
	new_m = New picture(p.width,p.height,32)
	new_mg=new_m.graphics
	new_mg.drawpicture p,0,0
	ps=new_m.RGBSurface
	for y=0 to new_mg.Height
			for x=0 to new_mg.Width
					if ps.Pixel(x,y)<>&cffffff then ps.Pixel(x,y)=&c000000
			next x
	next y
	
	
	new_p.ApplyMask new_m
	//
	
	t="icon_"+Left(s,Len(s)-7)+".png"
	
	f2=f.Parent.child(t)
	new_p.Save(f2,picture.SaveAsPNG)
	
	MsgBox "done"
	[/code]

Instead of newPic.Save(saveFoto, Picture.SaveAsPNG) create a new picture with Alpha Channel, draw newPic into it, and save it.

dim savePic as new Picture(newPic.Width, newPic.Height) savePic.Graphics.DrawPicture(newPic, 0, 0) savePic.Save(saveFoto, Picture.SaveAsPNG)

In older versions of Xojo than 2016R4 under Windows, make sure to set App.UseGDIPlus to True to avoid a PlatformNotSupportedException.

Thanks @Dave S !
Now I understood that should I create a mask pic first, fill it with black pixels and then apply it to my final pic.

Hi @Michel Bujardet ,
didn’t know that without the depth, the picture is with alpha channel. That way is much easier (and I think faster too) than with mask.

Thanks!