Created ImageLoader class.

Created ImageLoader class to load images.  Since Twitch doesn't always
send proper information about the file, we detect image format by the
file byte header, to ensure we are loading the correct image format.
This commit is contained in:
Mario Steele 2026-03-10 10:32:06 -05:00
parent eb64045e41
commit 4d6de8d46f
2 changed files with 57 additions and 0 deletions

56
lib/image_loader.gd Normal file
View file

@ -0,0 +1,56 @@
extends Node
var _client: BufferedHTTPClient
enum ImgFmt { PNG, JPG, WEBP, BMP, GIF, UNKNOWN }
func _identify_image(byte_array: PackedByteArray) -> ImgFmt:
if byte_array.size() < 8:
return ImgFmt.UNKNOWN
# PNG magic bytes: 0x89, P, N, G, \r, \n, 0x1a, \n
if byte_array[0] == 0x89 and byte_array[1] == 0x50 and byte_array[2] == 0x4E and byte_array[3] == 0x47:
return ImgFmt.PNG
# JPEG magic bytes (starts with 0xFF, 0xD8)
if byte_array[0] == 0xFF and byte_array[1] == 0xD8:
return ImgFmt.JPG
# WebP magic bytes (RIFF header, "WEBP" at offset 8)
if byte_array[0] == 0x52 and byte_array[1] == 0x49 and byte_array[2] == 0x46 and byte_array[3] == 0x46 and \
byte_array[8] == 0x57 and byte_array[9] == 0x45 and byte_array[10] == 0x42 and byte_array[11] == 0x50:
return ImgFmt.JPG
# BMP Magic (Starts with 0x42, 0x4D
if byte_array[0] == 0x42 and byte_array[1] == 0x4D:
return ImgFmt.BMP
if byte_array[0] == 0x47 and byte_array[1] == 0x49 and byte_array[2] == 0x46:
return ImgFmt.GIF
return ImgFmt.UNKNOWN
func _ready() -> void:
_client = BufferedHTTPClient.new()
_client.name = "ImageLoaderHTTPClient"
add_child(_client)
func load_image(url: String) -> ImageTexture:
var request : BufferedHTTPClient.RequestData = _client.request(url, HTTPClient.METHOD_GET, {}, "")
var response : BufferedHTTPClient.ResponseData = await _client.wait_for_request(request)
var img_buffer: PackedByteArray = response.response_data
var img: Image = Image.new()
match _identify_image(img_buffer):
ImgFmt.PNG:
img.load_png_from_buffer(img_buffer)
ImgFmt.JPG:
img.load_jpg_from_buffer(img_buffer)
ImgFmt.WEBP:
img.load_webp_from_buffer(img_buffer)
ImgFmt.BMP:
img.load_bmp_from_buffer(img_buffer)
ImgFmt.GIF:
push_error("Attempting to load a GIF image, use media loader to load.")
ImgFmt.UNKNOWN:
push_error("Failed to identify file!")
return ImageTexture.create_from_image(img)

1
lib/image_loader.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://b1m82tihhr2p7