Published
Edited
Dec 26, 2021
Importers
7 stars
Insert cell
Insert cell
Insert cell
function resize(
src, // URL of an image
width = 640, // Desired width
height = undefined // Desired height, undefined scales by aspect ratio
) {
// One cool thing about serverless cells and its code sharing is we can define the backend
// inline with the front end.
const backend = deploy("resizer", async (req, res) => {
const params = JSON.parse(decodeURIComponent(req.query.params))
const mime = "image/jpeg"
res.header("content-type", mime);
res.header("cache-control", "public, max-age=604800, immutable") // Remember
res.send(await convert(params.src, params.width, params.height, mime))
})
return `${backend.href}?params=${encodeURIComponent(JSON.stringify({
src, width, height
}))}`
}
Insert cell
Insert cell
Insert cell
function convert(src, width, height, mime) {
return new Promise(resolve => {
var img = new Image();
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height || ((img.height * canvas.width) / img.width);

var ctx = canvas.getContext("2d");
ctx.imageSmoothingQuality = "high"
// Resize
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

// https://stackoverflow.com/questions/47913980/js-convert-an-image-object-to-a-jpeg-file
canvas.toBlob(async (data)=> {
resolve(await data.arrayBuffer())
}, mime, 0.75);
};
img.src = src;
});
}
Insert cell
md`
## Example

### Too big!
![](${await FileAttachment("image.png").url()})

### Inline resizing
![](${resize(await FileAttachment("image.png").url(), 400)})
`
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more