CCCPaste

Godot - Load Image from URL

extends Control

export (String) var image_url = "https://filmsbykris.com/games/2021/cyber-griffin/website/images/kris.jpg"

func _ready():
	
	# Create an HTTP request node and connect its completion signal.
	var http_request = HTTPRequest.new()
	add_child(http_request)
	http_request.connect("request_completed", self, "_http_request_completed")

	# Perform the HTTP request. The URL below returns a PNG image as of writing.
	var error = http_request.request(image_url)
	if error != OK:
		push_error("An error occurred in the HTTP request.")

# Called when the HTTP request is completed.
func _http_request_completed(result, response_code, headers, body):
	var image = Image.new()
	var error = image.load_jpg_from_buffer(body)
	if error != OK:
		push_error("Couldn't load the image.")

	
	var texture = ImageTexture.new()
	#create texture. 
	#Flag 4 is needed 
	#or you get a black bot on some systems (Android)
	texture.create_from_image(image,4)

	# Display the image in a TextureRect node.
	var texture_rect = TextureRect.new()
	
	#Stretch image but keep aspect
	texture_rect.set_stretch_mode(6)
	
	#Center image
	texture_rect.set_margin(MARGIN_BOTTOM,get_viewport_rect().size.y)
	texture_rect.set_margin(MARGIN_RIGHT,get_viewport_rect().size.x)
	
	texture_rect.texture = texture
	add_child(texture_rect)