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

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more