diff --git a/lib/image_loader.gd b/lib/image_loader.gd new file mode 100644 index 00000000..2b631783 --- /dev/null +++ b/lib/image_loader.gd @@ -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) diff --git a/lib/image_loader.gd.uid b/lib/image_loader.gd.uid new file mode 100644 index 00000000..10b85724 --- /dev/null +++ b/lib/image_loader.gd.uid @@ -0,0 +1 @@ +uid://b1m82tihhr2p7