BMP file save for GLFW

Monkey Targets Forums/Desktop/BMP file save for GLFW

Fred(Posted 2013) [#1]
This is a very cheap BMP file class, but it does the job for a tool.
Class	BmpFile

	Field	Width:Int  			' bmp image width
	Field	Height:Int			' bmp image height
	
	Field	Pixels:Int[1]		' array for screen pixels

	Field	FileSize:Int		' bmp file size
	Field	Buffer:DataBuffer	' bmp file data (header + pixels)

	Field	PadLineWidth:Int	' bmp real line size
	
	' default header for 24bpp image
	Field	Header:Int[] = [ $42,$4D,$D6,$83,$00,$00,$00,$00,$00,$00,$36,$00,$00,$00,$28,$00,$00,$00,$6C,$00,$00,$00,$68,$00,$00,
							$00,$01,$00,$18,$00,$00,$00,$00,$00,$00,$00,$00,$00,$C3,$0E,$00,$00,$C3,$0E,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00 ]	
	Const	FILE_SIZE		:=	$2	
	Const	IMAGE_WIDTH		:=	$12
	Const	IMAGE_HEIGHT	:=	$16
	Const	RAW_DATA_SIZE	:=	$22

	Method Grab:Void( x:Int, y:Int, w:Int, h:Int )	' Call within OnRender after drawing the image to grab
	
		Width = w
		Height = h
		PadLineWidth = (((Width*3) + 3) / 4) * 4
	
		Pixels = Pixels.Resize( Width * Height )		
		ReadPixels Pixels, x, y, Width, Height 
			
		FileSize = Header.Length() + PadLineWidth * Height
		Buffer = New DataBuffer( FileSize )
		
		local ptr:Int
		for ptr = 0 until Header.Length
			Buffer.PokeByte ptr, Header[ptr]
		next
		
		Buffer.PokeInt FILE_SIZE, FileSize
		Buffer.PokeInt IMAGE_WIDTH, Width
		Buffer.PokeInt IMAGE_HEIGHT, Height
		Buffer.PokeInt RAW_DATA_SIZE, PadLineWidth * Height

		local i:Int = 0
		local pix:Int
		for local ys:Int = 0 until Height
			ptr = (Height - ys - 1) * PadLineWidth + Header.Length
			for local xs:Int = 0 until Width
				pix = Pixels[i]
				Buffer.PokeByte ptr+0, pix & $ff
				Buffer.PokeByte ptr+1, (pix shr 8) & $ff
				Buffer.PokeByte ptr+2, (pix shr 16) & $ff
				ptr += 3
				i += 1
			next
		next
		
	End
	  
	Method	Save:Void( filename:String )	' filename without .bmp

		Local file:=FileStream.Open( "monkey://internal/"+filename+".bmp","w" )
		If file
			file.Write Buffer, 0, FileSize
			file.Close
		Endif
		
	End
	
End

/edit for strict mode compatibilty


pyongpyong(Posted 2013) [#2]
Thank you!


mouser(Posted 2014) [#3]
Exactly what I was looking for. Thank you!


Supertino(Posted 2014) [#4]
booked-marked for possible future use. Thanks


skid(Posted 2014) [#5]
Merci beaucoup Fred.