Sling Academy
Home/Golang/How to convert PNG or JPEG images to WEBP in Go

How to convert PNG or JPEG images to WEBP in Go

Last updated: November 26, 2024

Image conversion is a common task in modern applications, especially when you're aiming to achieve optimal performance on web pages using lighter formats such as WEBP. Golang offers robust libraries to handle image processing, making it straightforward to convert PNG or JPEG images to the WEBP format. This article demonstrates how to perform these conversions using Go.

Setting Up Your Go Environment

Before we start, ensure that you have the Golang environment installed. You can download it from the official website. Verify your installation by running:

$ go version

To manage image formats, we'll use the popular "golang.org/x/image/webp" package, which can be installed using the following command:

$ go get golang.org/x/image/webp

Converting PNG to WEBP

Here's how you can convert a PNG image to the WEBP format using Go.

package main

import (
    "image/png"
    "os"
    "golang.org/x/image/webp"
)

func main() {
    // Open the PNG file
    pngFile, err := os.Open("input.png")
    if err != nil {
        panic(err)
    }
    defer pngFile.Close()

    // Decode the PNG image
    img, err := png.Decode(pngFile)
    if err != nil {
        panic(err)
    }

    // Create outputWEBP file
    webpFile, err := os.Create("output.webp")
    if err != nil {
        panic(err)
    }
    defer webpFile.Close()

    // Encode to WEBP
    if err := webp.Encode(webpFile, img, &webp.Options{Lossless: true}); err != nil {
        panic(err)
    }
    println("Image converted to WEBP successfully!")
}

Converting JPEG to WEBP

Similarly, you can convert a JPEG image to the WEBP format. See the code below:

package main

import (
    "image/jpeg"
    "os"
    "golang.org/x/image/webp"
)

func main() {
    // Open the JPEG file
    jpegFile, err := os.Open("input.jpg")
    if err != nil {
        panic(err)
    }
    defer jpegFile.Close()

    // Decode the JPEG image
    img, err := jpeg.Decode(jpegFile)
    if err != nil {
        panic(err)
    }

    // Create outputWEBP file
    webpFile, err := os.Create("output.webp")
    if err != nil {
        panic(err)
    }
    defer webpFile.Close()

    // Encode to WEBP
    if err := webp.Encode(webpFile, img, &webp.Options{Quality: 80}); err != nil {
        panic(err)
    }
    println("Image converted to WEBP successfully!")
}

Understanding WEBP Options

In the conversion functions listed above, the webp.Encode function takes an &webp.Options parameter, where:

  • Lossless: Set this to true for lossless conversion. Suitable for PNG images.
  • Quality: Ranges from 0 to 100. 0 being the lowest quality and highest compression, suitable for lossy JPEG conversions.

Conclusion

We've demonstrated how to convert PNG and JPEG images to the WEBP format in Go. Choosing WEBP over traditional formats like PNG or JPEG could significantly enhance web performance due to smaller file sizes, while still providing high quality.

Next Article: How to add watermark to an image in Go

Previous Article: How to resize images in Go

Series: File I/O and Operating System Interaction

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant