image attributes

BlitzMax Forums/BlitzMax Programming/image attributes

I have made these functions and so far for all png images it seems to work, but with the jpg I have found a few images where it shows the sizes divided by 10 and I have not figured out why yet. But its a start and perhaps someone can improve on it.

Local width:Int = 0
Local height:Int = 0

imageWidthHeightPNG("5.png",width,height)
Print Hex(width)+","+width
Print Hex(height)+","+height

imageWidthHeightJPG("5.jpg",width,height)
Print Hex(width)+","+width
Print Hex(height)+","+height

End

Function imageWidthHeightPNG(imagePath:String,width:Int Var, height:Int Var)
	Local file:TStream = OpenStream(imagePath)
	If ReadShort(file) <> $5089 Then Return False	' not a png image file
	SeekStream(file,18)
	width = ReadByte(file)*256
	width :+ ReadByte(file)
	SeekStream(file,22)
	height = ReadByte(file)*256
	height :+ ReadByte(file)
	CloseStream(file)
End Function

Function imageWidthHeightJPG(imagePath:String,width:Int Var, height:Int Var)
	Local file:TStream = OpenStream(imagePath)
	If ReadShort(file) <> $D8FF Then Return False	' not a jpg image file
	Local b1:Byte,b2:Byte,test:Byte=$E1
	Local jump:Int
	While Not Eof(file)
		' locate jump instructions
		Repeat
			b1 = ReadByte(file)
		Until b1 = $FF
		b2 = ReadByte(file)
		If b2 > $E0 And b2 < $EE Then	' jump instruction found
			jump = ReadByte(file)*256+ReadByte(file)
			SeekStream(file,StreamPos(file)+jump-2)
		End If
		If b2 = $EE Then	' no more jumps
			' find width & height info
			Repeat
				b1 = ReadByte(file)
				If b1 = $FF Then b2 = ReadByte(file)
			Until (b1 = $FF And b2 = $C0) Or (b1 = $FF And b2 = $C1) Or (b1 = $FF And b2 = $C2) Or (b1 = $FF And b2 = $C3)
			' skip 3 bytes
			SeekStream(file,StreamPos(file)+3)
			height = ReadByte(file)*256
			height :+ ReadByte(file)
			width = ReadByte(file)*256
			width :+ ReadByte(file)
			CloseFile(file)
			Return
		End If
	Wend
End Function


[edit] I think that I figured out the jpg function. Some jpg files has embedded thumbnail images, and those need to be jumped past to get to the info of the actual image. So far I have not found any jpg images the above function cannot handle.