Harbor

branch main
showing the latest snapshot on main
image.odin 1.3 KB · Plain text
gpu/resource/image.odin 0644 Raw
package resource

import "core:log"
import "core:os"
import "core:strings"
import "core:image"
import "core:image/png"
import "core:image/bmp"
import "core:image/tga"

// Load an image file and return raw RGBA pixel data.
// Caller must call destroy on the returned image when done.
load_image_from_file :: proc(path: string) -> (img: ^image.Image, ok: bool) {
	data, read_err := os.read_entire_file(path, context.allocator)
	if read_err != nil {
		log.errorf("gpu/resource: failed to read image file: %s", path)
		return nil, false
	}
	defer delete(data, context.allocator)

	options := image.Options{.alpha_add_if_missing}

	// Detect format by extension
	lower := strings.to_lower(path, context.temp_allocator)

	img_err: image.Error
	if strings.has_suffix(lower, ".png") {
		img, img_err = png.load_from_bytes(data, options)
	} else if strings.has_suffix(lower, ".bmp") {
		img, img_err = bmp.load_from_bytes(data, options)
	} else if strings.has_suffix(lower, ".tga") {
		img, img_err = tga.load_from_bytes(data, options)
	} else {
		// Try generic loader (auto-detect by magic bytes)
		img, img_err = image.load_from_bytes(data, options)
	}

	if img_err != nil {
		log.errorf("gpu/resource: failed to decode image %s: %v", path, img_err)
		return nil, false
	}

	return img, true
}

destroy_image :: proc(img: ^image.Image) {
	image.destroy(img)
}