Files
cell-image/examples/convert.ce
2026-01-18 11:23:38 -06:00

114 lines
3.0 KiB
Plaintext

/*
* Image Converter - Command line tool
*
* Usage: cell run convert.ce <input_file> <output_file>
* Example: cell run convert.ce lenna.png lenna.qoi
*
* Supported formats:
* - Decode: png, jpg, bmp, tga, gif, psd, qoi, ase/aseprite
* - Encode: png, jpg, bmp, tga, qoi
*/
var io = use('fd')
var png = use('png')
var jpg = use('jpg')
var bmp = use('bmp')
var tga = use('tga')
var gif = use('gif')
var psd = use('psd')
var qoi = use('qoi')
var aseprite = use('aseprite')
if (length(args) < 2) {
log.console("Usage: cell run convert.ce <input_file> <output_file>")
log.console("Example: cell run convert.ce lenna.png lenna.qoi")
log.console("Decode: png, jpg, bmp, tga, gif, psd, qoi, ase/aseprite")
log.console("Encode: png, jpg, bmp, tga, qoi")
$stop()
}
var input_file = args[0]
var output_file = args[1]
function ext_lower(path) {
var e = array(path, '.').pop()
if (!e) return null
return lower(e)
}
function decode_image(blob, ext) {
switch (ext) {
case 'png': return png.decode(blob)
case 'jpg': case 'jpeg': return jpg.decode(blob)
case 'bmp': return bmp.decode(blob)
case 'tga': return tga.decode(blob)
case 'gif': return gif.decode(blob)
case 'psd': return psd.decode(blob)
case 'qoi': return qoi.decode(blob)
case 'ase': case 'aseprite': return aseprite.decode(blob)
default:
// Try common decoders as a fallback
var decoders = [png.decode, jpg.decode, qoi.decode, aseprite.decode]
for (var i = 0; i < length(decoders); i++) {
try {
var r = decoders[i](blob)
if (r) return r
} catch (e) {}
}
return null
}
}
function encode_image(img, ext) {
switch (ext) {
case 'png': return png.encode(img)
case 'jpg': case 'jpeg': return jpg.encode(img)
case 'bmp': return bmp.encode(img)
case 'tga': return tga.encode(img)
case 'qoi':
if (!img.format) img.format = "rgba32"
return qoi.encode(img)
default:
return null
}
}
log.console("Loading input image: " + input_file)
var input_blob = io.slurp(input_file)
if (!input_blob) {
log.console("Error: Could not load input file: " + input_file)
$stop()
}
var input_ext = ext_lower(input_file)
var decoded = decode_image(input_blob, input_ext)
if (!decoded) {
log.console("Error: Failed to decode image: " + input_file)
$stop()
}
log.console("Image loaded: " + text(decoded.width) + "x" + text(decoded.height) + " pixels")
var output_ext = ext_lower(output_file)
if (!output_ext) {
log.console("Error: Could not determine output format from: " + output_file)
$stop()
}
log.console("Converting to format: " + output_ext)
var encoded = encode_image(decoded, output_ext)
if (!encoded) {
log.console("Error: Failed to encode image to format: " + output_ext)
$stop()
}
var success = io.slurpwrite(output_file, encoded.pixels)
if (!success) {
log.console("Error: Could not save output file: " + output_file)
$stop()
}
log.console("Successfully converted " + input_file + " to " + output_file)
log.console("Output size: " + text(length(encoded.pixels)) + " bytes")