Advertisement
metalx1000

Godot - Load Image from URL

Mar 17th, 2021
3,690
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. extends Control
  2.  
  3. export (String) var image_url = "https://filmsbykris.com/games/2021/cyber-griffin/website/images/kris.jpg"
  4.  
  5. func _ready():
  6.    
  7.     # Create an HTTP request node and connect its completion signal.
  8.     var http_request = HTTPRequest.new()
  9.     add_child(http_request)
  10.     http_request.connect("request_completed", self, "_http_request_completed")
  11.  
  12.     # Perform the HTTP request. The URL below returns a PNG image as of writing.
  13.     var error = http_request.request(image_url)
  14.     if error != OK:
  15.         push_error("An error occurred in the HTTP request.")
  16.  
  17. # Called when the HTTP request is completed.
  18. func _http_request_completed(result, response_code, headers, body):
  19.     var image = Image.new()
  20.     var error = image.load_jpg_from_buffer(body)
  21.     if error != OK:
  22.         push_error("Couldn't load the image.")
  23.  
  24.    
  25.     var texture = ImageTexture.new()
  26.     #create texture.
  27.     #Flag 4 is needed
  28.     #or you get a black bot on some systems (Android)
  29.     texture.create_from_image(image,4)
  30.  
  31.     # Display the image in a TextureRect node.
  32.     var texture_rect = TextureRect.new()
  33.    
  34.     #Stretch image but keep aspect
  35.     texture_rect.set_stretch_mode(6)
  36.    
  37.     #Center image
  38.     texture_rect.set_margin(MARGIN_BOTTOM,get_viewport_rect().size.y)
  39.     texture_rect.set_margin(MARGIN_RIGHT,get_viewport_rect().size.x)
  40.    
  41.     texture_rect.texture = texture
  42.     add_child(texture_rect)
  43.    
  44.  
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement