Replace color of an image in godot 4

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By zkmark

Replace color of an image in godot 4

I’m trying to change the image color of a node, but I’m getting various errors with the version 3 code

I used the tutorial in this video

But apparently image.lock() and image.unlock();
so comment those parts

extends Node2D

@export_color_no_alpha var origin = Color("#ff0000")
@export_color_no_alpha var new_color
@onready var MyImage : Sprite2D = $MyImage

func _ready():
	change_color()

func change_color():
	#var image: Image = self.texture.get_data()
	var image: Image = MyImage.texture.get_image()
	#image.lock()
	for y in image.get_height():
		for x in image.get_width():
			if image.get_pixel(x, y) == origin:
				image.set_pixel(x, y, new_color)
	#image.unlock();

	var new_texture = ImageTexture.new()
	#new_texture.create_from_image(image, 0)
	new_texture.create_from_image(image)
	MyImage.texture = new_texture

How could I change the color of an image by code?

:bust_in_silhouette: Reply From: zkmark

I was able to solve it in the following way it already changes the color

Is my code ok? Or am I using bad practices?

extends Node2D

@export_color_no_alpha var origin = Color("#ff0000")
@export_color_no_alpha var new_color
@onready var MyImage : Sprite2D = $MyImage

func _ready():
	change_color()

func change_color():
	var image: Image = MyImage.texture.get_image()

	for y in image.get_height():
		for x in image.get_width():
			if image.get_pixel(x, y) == origin:
				image.set_pixel(x, y, new_color)

	var new_texture = ImageTexture.create_from_image(image)
	MyImage.texture = new_texture

.