I'm new to golang and I'm trying to get the image size of all the images listed in a directory. That's what I've done
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've an error when it comes to image.DecodeConfig
, that says image: unknown format
Has someone an idea about the proper way to do it?
In the docs here http://golang.org/src/pkg/image/format.go?s=2676:2730#L82 says that i should pass a io.Reader
as argument, and that's what i'm doing.
There are two problems with your code.
The first one is that you have inverted the test err != nil
, so you try to decode the image only in the case where you have an error. It should be err == nil
.
The second one, as said by jimt, is that you use filepath.Name()
, which contains only the file name in os.Open()
, this is what makes err
to always be set, thus always entering in the if
, and decoding a file that doesn't exists.
Here is the corrected code :
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)
}
}
}
Also, don't forget to add other imports than image/jpeg
if you have other images formats in your dir.
In case if you want to get width and height of image by use image.Decode(reader) without image.DecodeConfig
m, _, err := image.Decode(reader)
if err != nil {
log.Fatal(err)
}
bounds := m.Bounds()
w := bounds.Dx()
h := bounds.Dy()
fmt.Printf("width: %d, height: %d\n", w, h)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With