Sling Academy
Home/Golang/How to resize images in Go

How to resize images in Go

Last updated: November 26, 2024

Image processing is a common task for many applications, and Go offers an efficient way to perform image resizing using packages such as image and github.com/nfnt/resize. In this article, I will show you how to resize images in Go with step-by-step instructions and examples.

Installing the Required Packages

First, make sure you have Go installed on your machine. You can check the Go installation by running the command in your terminal:

go version

To start using the resize package, you need to install it using the Go package manager. Run the following command to install:

go get github.com/nfnt/resize

Reading an Image in Go

Before you can resize an image, you need to read it into your Go program. Here’s how you can do it using the image and os packages:

package main

import (
    "image"
    "image/jpeg"  // You may add other formats such as image/png for PNG files
    "os"
    "log"
)

func main() {
    file, err := os.Open("sample.jpg")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    img, _, err := image.Decode(file)
    if err != nil {
        log.Fatal(err)
    }

    // Now img variable holds the image file data
}

Resizing the Image

Once the image is loaded into memory, you can use the github.com/nfnt/resize package to resize it:

import (
    "github.com/nfnt/resize"
)

func main() {
    // Read the image as shown above...

    // Resize image to width 200 using Lanczos resampling
    // and preserve aspect ratio
    newImage := resize.Resize(200, 0, img, resize.Lanczos3)
}

In the example above, the resize.Resize() function is used to scale the image to a width of 200 pixels. The second argument is set to 0 to ensure the aspect ratio is maintained. The last parameter resize.Lanczos3 is used for high-quality image processing.

Saving the Resized Image

After resizing the image, the last step is to save it. Use the os and jpeg packages:

outputFile, err := os.Create("resized.jpg")
if err != nil {
    log.Fatal(err)
}
defer outputFile.Close()

jpeg.Encode(outputFile, newImage, nil)

This code creates a new file named resized.jpg and writes the resized image to it in JPEG format. Adjust the encoding for other formats like PNG if necessary.

Conclusion

Go provides comprehensive libraries for basic and advanced image processing tasks. By combining the image and resize packages, you can easily accomplish tasks such as image resizing. This capability is useful for web applications, batch processing systems, and any Go-based software that requires image manipulation.

Next Article: How to convert PNG or JPEG images to WEBP in Go

Previous Article: How to automatically generate unique file names 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