Skip to content
Cloudflare Docs

Watermarks

Last reviewed: 11 months ago

Draw a watermark from KV on an image from R2

JavaScript
export default {
async fetch(request, env, ctx) {
const watermarkKey = "my-watermark";
const sourceKey = "my-source-image";
const cache = await caches.open("transformed-images");
const cacheKey = new URL(sourceKey + "/" + watermarkKey, request.url);
const cacheResponse = await cache.match(cacheKey);
if (cacheResponse) {
return cacheResponse;
}
let watermark = await env.NAMESPACE.get(watermarkKey, "stream");
let source = await env.BUCKET.get(sourceKey);
if (!watermark || !source) {
return new Response("Not found", { status: 404 });
}
const result = await env.IMAGES.input(source.body)
.draw(watermark)
.output({ format: "image/jpeg" });
const response = result.response();
ctx.waitUntil(cache.put(cacheKey, response.clone()));
return response;
},
};