Custom file type

BlitzPlus Forums/BlitzPlus Programming/Custom file type

Global life=0
Global antialias_on=0
Global something$="hello there"

Graphics 640,480,0,2
SetBuffer BackBuffer()


; to save test
image=LoadImage("test.png")
saveGame("test.dat",image)

FreeImage image ; get rid of our loaded image
Print "Save file saved. Press any key to load it."
WaitKey

; to load test (loads settings AND a new image);
image=loadGame("test.dat")
DrawImage image,0,40
Flip
Print "Done!"
WaitKey
End






; this function saves an image as well as other information in the file
Function saveGame(file$,image)
	If image=0 Then Return
	f=WriteFile(file)
	WriteString f,"File version: 1"
	WriteInt f,life
	WriteByte f,antialias_on
	WriteString f,something
	
	; write w + h
	WriteInt f,ImageWidth(image)
	WriteInt f,ImageHeight(image)
	
	; now write the image
	LockBuffer ImageBuffer(image)
	For i=0 To ImageWidth(image)-1
		For j=0 To ImageHeight(image)-1
			rgb=ReadPixelFast(i,j,ImageBuffer(image))
			WriteInt f,rgb
		Next
	Next
	UnlockBuffer ImageBuffer(image)	
	CloseFile f ; close the file
End Function


; this function returns a new image loaded from the file
Function loadGame(file$)
 ; now do the EXACT opposite here.
	f=ReadFile(file)
	
	file_ver$=ReadString(f)
	life=ReadInt(f)
	antialias_on=ReadByte(f)
	something=ReadString(f)
	
	w=ReadInt(f)
	h=ReadInt(f)
	
	; create a new image
	image=CreateImage(w,h)
	
	; now read the image
	LockBuffer ImageBuffer(image)
	For i=0 To w-1
		For j=0 To h-1
			rgb=ReadInt(f)
			WritePixelFast(i,j,rgb,ImageBuffer(image))
		Next
	Next
	UnlockBuffer ImageBuffer(image)
	
	CloseFile f
	Return image
End Function