Modern browser sandbox implementation based on ImageBitmap and OffscreenCanvas. Use it as a drop-in tool-call backend or adaptation template.
async function main(args) {
const {
input_base64,
quality = 0.8,
max_width = 0,
output_format = "image/jpeg",
} = args;
if (!input_base64) {
return { success: false, result: "", error: "input_base64 is required" };
}
try {
const base64Data = input_base64.replace(/^data:[^;]+;base64,/, "");
const binaryString = atob(base64Data);
const bytes = Uint8Array.from(binaryString, (char) => char.charCodeAt(0));
const blob = new Blob([bytes]);
const image = await createImageBitmap(blob);
let { width, height } = image;
if (max_width > 0 && width > max_width) {
const ratio = max_width / width;
width = max_width;
height = Math.round(height * ratio);
}
const canvas = new OffscreenCanvas(width, height);
const ctx = canvas.getContext("2d");
if (!ctx) {
throw new Error("Canvas context unavailable");
}
ctx.drawImage(image, 0, 0, width, height);
let targetFormat = output_format;
let outputBlob;
try {
outputBlob = await canvas.convertToBlob({
type: targetFormat,
quality: targetFormat === "image/png" ? undefined : quality,
});
} catch {
targetFormat = "image/webp";
outputBlob = await canvas.convertToBlob({ type: targetFormat, quality });
}
const buffer = await outputBlob.arrayBuffer();
const outputBase64 = btoa(
Array.from(new Uint8Array(buffer), (byte) => String.fromCharCode(byte)).join("")
);
return {
success: true,
result: "data:" + targetFormat + ";base64," + outputBase64,
mime_type: targetFormat,
original_size: bytes.length,
compressed_size: outputBlob.size,
width,
height,
};
} catch (error) {
return {
success: false,
result: "",
error: "Compression failed: " + (error instanceof Error ? error.message : String(error)),
};
}
}