Developer Tools & Snippets
Common JavaScript snippets for client-side image manipulation using modern browser APIs.
resize
async function resizeImage(file, width, height) {
const bmp = await createImageBitmap(file);
const canvas = new OffscreenCanvas(width, height);
const ctx = canvas.getContext('2d');
ctx.drawImage(bmp, 0, 0, width, height);
const blob = await canvas.convertToBlob({ type: 'image/jpeg' });
return blob;
}convert
async function convertToWebP(file) {
const bmp = await createImageBitmap(file);
const canvas = new OffscreenCanvas(bmp.width, bmp.height);
const ctx = canvas.getContext('2d');
ctx.drawImage(bmp, 0, 0);
const blob = await canvas.convertToBlob({ type: 'image/webp', quality: 0.8 });
return blob;
}pixel Data
async function getPixelData(file) {
const bmp = await createImageBitmap(file);
const canvas = new OffscreenCanvas(bmp.width, bmp.height);
const ctx = canvas.getContext('2d');
ctx.drawImage(bmp, 0, 0);
const imageData = ctx.getImageData(0, 0, bmp.width, bmp.height);
// imageData.data is a Uint8ClampedArray of [R, G, B, A, R, G, B, A, ...]
return imageData.data;
}