You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/content/docs/images/transform-images/transform-via-workers.mdx
+50-52Lines changed: 50 additions & 52 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -205,67 +205,65 @@ if (response.ok || response.redirected) {
205
205
Assuming you [set up a Worker](/workers/get-started/guide/) on `https://example.com/image-resizing` to handle URLs like `https://example.com/image-resizing?width=80&image=https://example.com/uploads/avatar1.jpg`:
206
206
207
207
```js
208
-
addEventListener("fetch", event => {
209
-
event.respondWith(handleRequest(event.request))
210
-
})
211
-
212
208
/**
213
209
* Fetch and log a request
214
210
* @param {Request} request
215
211
*/
216
-
async function handleRequest(request) {
217
-
// Parse request URL to get access to query string
218
-
let url = new URL(request.url)
219
-
220
-
// Cloudflare-specific options are in the cf object.
221
-
let options = { cf: { image: {} } }
222
-
223
-
// Copy parameters from query string to request options.
224
-
// You can implement various different parameters here.
225
-
if (url.searchParams.has("fit")) options.cf.image.fit = url.searchParams.get("fit")
226
-
if (url.searchParams.has("width")) options.cf.image.width = url.searchParams.get("width")
227
-
if (url.searchParams.has("height")) options.cf.image.height = url.searchParams.get("height")
228
-
if (url.searchParams.has("quality")) options.cf.image.quality = url.searchParams.get("quality")
229
-
230
-
// Your Worker is responsible for automatic format negotiation. Check the Accept header.
231
-
const accept = request.headers.get("Accept");
232
-
if (/image\/avif/.test(accept)) {
233
-
options.cf.image.format = 'avif';
234
-
} else if (/image\/webp/.test(accept)) {
235
-
options.cf.image.format = 'webp';
236
-
}
237
-
238
-
// Get URL of the original (full size) image to resize.
239
-
// You could adjust the URL here, e.g., prefix it with a fixed address of your server,
240
-
// so that user-visible URLs are shorter and cleaner.
241
-
const imageURL = url.searchParams.get("image")
242
-
if (!imageURL) return new Response('Missing "image" value', { status: 400 })
243
-
244
-
try {
245
-
// TODO: Customize validation logic
246
-
const { hostname, pathname } = new URL(imageURL)
247
-
248
-
// Optionally, only allow URLs with JPEG, PNG, GIF, or WebP file extensions
0 commit comments