Find the Size of an Image in Go



In this tutorial, we will learn how to find the size of an image in Go. We will cover the basic concept of image processing and use the 'image' and 'os' packages to get the dimensions of an image.


What is Image Processing

Image processing involves performing operations on images to extract useful information or to modify the image in some way. Finding the size of an image is a common task in image processing.


Syntax

The syntax to find the size of an image in Go using the 'image' and 'os' packages is:

import (
    "fmt"
    "image"
    _ "image/jpeg"
    _ "image/png"
    "os"
)

func getImageSize(filePath string) (int, int, error) {
    file, err := os.Open(filePath)
    if err != nil {
        return 0, 0, err
    }
    defer file.Close()
    img, _, err := image.DecodeConfig(file)
    if err != nil {
        return 0, 0, err
    }
    return img.Width, img.Height, nil
}


Example 1: Finding the size of an image

We can create a function to find the size of an image by opening the image file and getting its dimensions using the 'image' and 'os' packages.

For example,

  1. Import the fmt, image, os packages and the image formats you need to support (e.g., _ "image/jpeg", _ "image/png").
  2. Define a function named getImageSize that takes one parameter filePath of type string and returns the width, height, and an error.
  3. Use os.Open to open the image file. If an error occurs, return 0, 0, and the error.
  4. Use defer to close the file after the function completes.
  5. Use image.DecodeConfig to decode the image configuration and get the width and height. If an error occurs, return 0, 0, and the error.
  6. Return the width and height of the image.
  7. In the main function, call the getImageSize function with a sample image file path and print the result.

Go Program

package main

import (
    "fmt"
    "image"
    _ "image/jpeg"
    _ "image/png"
    "os"
)

func getImageSize(filePath string) (int, int, error) {
    file, err := os.Open(filePath)
    if err != nil {
        return 0, 0, err
    }
    defer file.Close()
    img, _, err := image.DecodeConfig(file)
    if err != nil {
        return 0, 0, err
    }
    return img.Width, img.Height, nil
}

func main() {
    // Sample image file path
    imagePath := "sample_image.jpg"

    // Get the size of the image
    width, height, err := getImageSize(imagePath)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    // Print the result
    fmt.Printf("Size of the image is: %dx%d\n", width, height)
}

Output

Size of the image is: 1024x768