Get image size using golang

I am new to golang and I am trying to get the image size of all the images listed in the directory. This is what I did

package main

import (
    "fmt"
    "image"
    _ "image/jpeg"
    "io/ioutil"
    "os"
)

const dir_to_scan string = "/home/da/to_merge"

func main() {
    files, _ := ioutil.ReadDir(dir_to_scan)
    for _, filepath := range files {

        if reader, err := os.Open(filepath.Name()); err != nil {
            defer reader.Close()
            im, _, err := image.DecodeConfig(reader)
            if err != nil {
                fmt.Fprintf(os.Stderr, "%s: %v\n", filepath.Name(), err)
                continue
            }
            fmt.Printf("%s %d %d\n", filepath.Name(), im.Width, im.Height)
        } else {
            fmt.Println("Impossible to open the file")
        }
    }
}

I have a mistake when it comes to image.DecodeConfigwhich says image: unknown format Does anyone have an idea of ​​the right way to do this? The docs here http://golang.org/src/pkg/image/format.go?s=2676:2730#L82 says that I should pass the argument io.Readeras an argument, and that is what I am doing.

+3
source share
1 answer

There are two problems in the code.

-, err != nil, , . err == nil.

, jimt, , filepath.Name(), os.Open(), , err, if , .

:

package main

import (
    "fmt"
    "image"
    _ "image/jpeg"
    "io/ioutil"
    "os"
    "path/filepath"
)

const dir_to_scan string = "/home/da/to_merge"

func main() {
    files, _ := ioutil.ReadDir(dir_to_scan)
    for _, imgFile := range files {

        if reader, err := os.Open(filepath.Join(dir_to_scan, imgFile.Name())); err == nil {
            defer reader.Close()
            im, _, err := image.DecodeConfig(reader)
            if err != nil {
                fmt.Fprintf(os.Stderr, "%s: %v\n", imgFile.Name(), err)
                continue
            }
            fmt.Printf("%s %d %d\n", imgFile.Name(), im.Width, im.Height)
        } else {
            fmt.Println("Impossible to open the file:", err)
        }
    }
}

, , image/jpeg, .

+4

All Articles