Resizing Image

In this document, we demonstrate how to identify the client type via User-Agent in the request header, use fetch API to get the image from the origin, and convert it to the format required by the browser.

Sample Code

addEventListener('fetch', event => {
  // If the function code throws an unhandled exception, Edge Functions forwards the current request back to the origin. 
  event.passThroughOnException();
  event.respondWith(handleEvent(event));
});

async function handleEvent(event) {
  const { request } = event;
  const urlInfo = new URL(request.url);
  const userAgent = request.headers.get('user-agent');

  // Request a non-image resource
  if (!/\.(jpe?g|png)$/.test(urlInfo.pathname)) {
    return fetch(request);
  }

  // Image width on the mobile device
  let width = 480;
  const isPcClient = isPc(userAgent);

  // Image width on the PC
  if (isPcClient) {
    width = 1280;
  }

  // Scale the image
  const response = await fetch(request, {
    eo: {
      image: {
        width,
      }
    }
  });

  // Set the response header
  response.headers.set('x-ef-client', isPcClient ? 'pc' : 'mobile');
  return response;
}

// Identify the request client type
function isPc(userAgent) {
  const regex = /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i;
 
  if(regex.test(userAgent)) {
    return false;
  }
  
  return true;
}

Sample Preview

In the address bar of the browser, enter a URL (such as https://example.com/images-resize/ef-1.jpeg) that matches a trigger rule of the Edge Function to preview the effect of the sample code.

  1. For displaying on PC, scale the image to 1280 x 720.

16.1.png

  1. For displaying on mobile devices, scale the image to 480 x 270.

16.2.png

References

  1. Runtime APIs: Fetch
  2. Runtime APIs: Headers
  3. Runtime APIs: Response
  4. Runtime APIs: Request