tencent cloud

Feedback

Adaptive Image Format Conversion

Last updated: 2023-07-06 17:19:11
    In this document, we demonstrate how to identify the browser 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.
    // Browser image format
    const broswerFormat = {
    Chrome: 'webp',
    Opera: 'webp',
    Firefox: 'webp',
    Safari: 'jp2',
    Edge: 'webp',
    IE: 'jxr'
    };
    
    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 userAgent = request.headers.get('user-agent');
    const bs = getBroswer(userAgent);
    const format = broswerFormat[bs];
    // Do not convert the image format
    if (!format) {
    return fetch(request);
    }
    
    // Convert image format
    const response = await fetch(request, {
    eo: {
    image: {
    format
    }
    }
    });
    
    // Set the response header
    response.headers.set('x-ef-format', format);
    return response;
    }
    
    function getBroswer(userAgent) {
    if (/Edg/i.test(userAgent)) {
    return 'Edge'
    }
    if (/Trident/i.test(userAgent)) {
    return 'IE'
    }
    if (/Firefox/i.test(userAgent)) {
    return 'Firefox';
    }
    if (/Chrome/i.test(userAgent)) {
    return 'Chrome';
    }
    if (/Opera|OPR/i.test(userAgent)) {
    return 'Opera';
    }
    if (/Safari/i.test(userAgent)) {
    return 'Safari'
    }
    }
    

    Sample Preview

    In the address bar of the browser, enter a URL (such as https://example.com/images-format/ef-1.jpeg) that matches a trigger rule of the edge function to preview the effect of the sample code.
    
    Google Chrome: webp
    
    Apple Safari: jp2
    
    Microsoft IE: jxr
    

    References

    
    Contact Us

    Contact our sales team or business advisors to help your business.

    Technical Support

    Open a ticket if you're looking for further assistance. Our Ticket is 7x24 avaliable.

    7x24 Phone Support