# Derived from https://github.com/jegor377/godot-gdgifexporter @tool extends EditorImportPlugin func _can_import_threaded(): return false func _get_priority(): return 100 func _get_import_order(): # 数字越小越提前 return ResourceImporter.IMPORT_ORDER_DEFAULT - 100 func _get_importer_name(): return "gif.animated.texture.plugin" func _get_visible_name(): return "Sprite Frames (Thread Safe)" func _get_recognized_extensions(): return ["gif"] func _get_save_extension(): return "tres" func _get_resource_type(): return "SpriteFrames" func _get_preset_count(): return 0 func _get_preset_name(i): return "" func _get_import_options(_path, _i): return [] func _get_option_visibility(path: String, option_name: StringName, options: Dictionary) -> bool: return false # 防止同时加载多个文件时卡死 static var MUTEX = Mutex.new() const gif_dir = "res://asset/art/gif/" func _import(source_file, save_path, options, platform_variants, gen_files): if GifManager == null: printerr("GifManager is not available!") return FAILED var file = FileAccess.open(source_file, FileAccess.READ) var buffer = file.get_buffer(file.get_length()) file.close() MUTEX.lock() var frames = GifManager.sprite_frames_from_buffer(buffer, 0, 30) var filename = save_path + "." + _get_save_extension() var code = ResourceSaver.save(frames, filename) # await get_tree().create_timer(0.1).timeout MUTEX.unlock() print_debug("Imported GIF frames: ", frames.get_frame_count("gif"), " from ", source_file) var base_dir = source_file.get_base_dir() if base_dir != gif_dir and base_dir.begins_with(gif_dir): var animation_name = source_file.get_file().replace(".gif", "") var dir_name = base_dir + "/" + animation_name + "/" if DirAccess.dir_exists_absolute(dir_name): DirAccess.remove_absolute(dir_name) DirAccess.make_dir_absolute(dir_name) var sprite_frames_path = base_dir + "/frames.tres" var sprite_frames: SpriteFrames if not FileAccess.file_exists(sprite_frames_path): sprite_frames = SpriteFrames.new() sprite_frames.resource_path = sprite_frames_path else: sprite_frames = load(sprite_frames_path) as SpriteFrames if sprite_frames.has_animation(animation_name): sprite_frames.clear(animation_name) else: sprite_frames.add_animation(animation_name) sprite_frames.set_animation_loop(animation_name, frames.get_animation_loop("gif")) sprite_frames.set_animation_speed(animation_name, frames.get_animation_speed("gif")) for i in range(frames.get_frame_count("gif")): var texture = frames.get_frame_texture("gif", i) as Texture2D var image = texture.get_image() var image_path = dir_name + str(i) + ".png" image.save_png(image_path) texture = ImageTexture.create_from_image(image) texture.take_over_path(image_path) var duration = frames.get_frame_duration("gif", i) sprite_frames.add_frame(animation_name, texture, duration) print_debug("Created images and added to SpriteFrames: ", animation_name) ResourceSaver.save(sprite_frames) return code