Efficient WebP Conversion Using Edge Computing

mpoiiii

mpoiiii

Posted on September 5, 2024

Efficient WebP Conversion Using Edge Computing

Introduction

This article primarily introduces seamless image conversion technology based on cloud services. The main focus is on the mutual conversion between WebP and various traditional formats. This is because WebP outperforms traditional JPG and PNG formats in many aspects, but its drawback lies in poor compatibility, making it unviewable on some older devices.

This article will explore how to achieve seamless image conversion through edge computing functions in cloud services, thereby automatically ensuring compatibility with various versions of devices.

Basic Concepts

What is the WebP image format?

WebP is a modern image format developed by Google, designed to provide more efficient image compression while maintaining high image quality. Here is Google's detailed explanation of the WebP format.

WebP images have features like efficient compression, high image quality, and bandwidth savings. The WebP format significantly enhances loading speed, image quality, and bandwidth efficiency, making it an indispensable image format in the modern web.

What is edge computing?

Edge computing is introduced here because converting a large number of images consumes a lot of computing resources, and edge computing can effectively address this issue. By performing image conversion tasks on edge devices, the load on the central server can be significantly reduced, and processing efficiency can be improved.

Edge Computing is a distributed computing paradigm that moves computation and data storage closer to the data source (the "edge") rather than relying on a central data center.

Edge computing helps reduce latency, lower bandwidth consumption, and improve real-time processing capabilities. It is often used in scenarios requiring rapid response and low latency, such as the Internet of Things (IoT), smart cities, industrial automation, and autonomous driving.

Overall Process

Developers upload traditional format images (such as JPG, PNG) to a static resource server, for example, to the service address at example.com/asset/img. When users access this domain to retrieve static resources, the system can determine the user's device and browser type by checking the user-agent.

The system determines whether the user's device and browser support the WebP format based on device and version information. If supported, the system will prioritize providing WebP format images; if not, it will continue to provide the original JPG or PNG format images.

Even though users access the domain example.com/asset/img, different static resources are transmitted based on the judgment of the user's device. For devices that support WebP, users will receive smaller and higher-quality WebP images; for devices that do not support WebP, users will still receive compatible JPG or PNG images.

When users upload static images, the images can be converted at the edge node before being transmitted to the static resource server.

The system executes EdgeRoutine through edge computing technology. Edge computing processes data in real-time at network nodes close to users, reducing latency and bandwidth consumption. This way, images can be converted at the edge node before being transmitted to the static resource server, enhancing processing efficiency and user experience.

Detailed Implementation

The core implementation of the program is the conversion of PNG, JPG formats to WebP format. Several challenges need to be addressed:

  1. Quality and File Size Balance: Finding the optimal balance between image quality and file size is essential. Over-compression may degrade image quality, while under-compression may not fully leverage WebP's advantages.
  2. Data Conversion: PNG, JPG, and WebP have differences in color management and metadata handling. These differences need to be managed during conversion to ensure the resulting WebP images maintain the visual quality and functionality of the original images.
# This uses Python's Pillow library to convert PNG, JPG to WebP
def convert_image_to_webp(input_path, output_path, quality=80):
  """
  :param input_path: str, path to the input PNG/JPG image
  :param output_path: str, path to save the converted WebP image
  :param quality: int, quality of the output WebP image (1-100)
  """
  try:
      # Open the input image
      with Image.open(input_path) as img:
          # Preserve color profile (ICC profile)
          icc_profile = img.info.get('icc_profile')

          # Preserve metadata
          metadata = img.info

          # Convert and save as WebP
          img.save(output_path, 'WEBP', quality=quality, icc_profile=icc_profile, **metadata)

          print(f"Image converted to WebP format and saved at {output_path}")

  except Exception as e:
      print(f"An error occurred: {e}")
Enter fullscreen mode Exit fullscreen mode
  1. Transparency Handling: PNG is often used for images requiring transparent backgrounds, and WebP also supports transparency (Alpha channel). Ensuring transparency effects are maintained during conversion may require additional processing steps.

  2. Computational Resource Consumption: The image conversion process consumes computational resources. Converting many images simultaneously can significantly load the server, necessitating effective resource management and optimization.

To address the resource consumption associated with processing many images, edge computing technology is typically employed. By executing edge computing functions on edge devices, image conversion tasks can be effectively completed, optimizing resource usage and achieving seamless user image transmission.

The remaining part is the execution of edge functions. Here, it is set to transmit different images according to different browsers.

// Browser image format usage
const broswerFormat = {
  Chrome: 'webp',
  Opera: 'webp',
  Firefox: 'webp',
  Safari: 'jp2',
  Edge: 'webp',
  IE: 'jxr'
};

addEventListener('fetch', event => {
  // When the function code throws an unhandled exception, the edge function will forward this 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];

  // No need to convert image format
  if (!format) {
    return fetch(request);
  }

  // Image format conversion
  const response = await fetch(request, {
    eo: {
      image: {
        format
      }
    }
  });

  // Set response header
  response.headers.set('x-ef-format', format);
  return response;
}

function getBroswer(userAgent) {
  if (/Edg/i.test(userAgent)) {
    return 'Edge'
  }
  else if (/Trident/i.test(userAgent)) {
    return 'IE'
  } else if

  ······
}
Enter fullscreen mode Exit fullscreen mode

This is an image conversion tool I completed relying on edge computing. You can experience it (webp to jpg, webp to png, webp to gif). Its speed can beat most image conversion tools on the market, and it handles many image conversions with ease.

💖 💪 🙅 🚩
mpoiiii
mpoiiii

Posted on September 5, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Efficient WebP Conversion Using Edge Computing
edgecomputing Efficient WebP Conversion Using Edge Computing

September 5, 2024