Get image size with golang

huangapple go评论81阅读模式
英文:

Get image size with golang

问题

我是你的中文翻译助手,以下是你提供的代码的翻译:

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("无法打开文件")
		}
	}
}

当使用image.DecodeConfig时,我遇到了一个错误,提示image: unknown format。有人知道正确的方法吗?在这里的文档中http://golang.org/src/pkg/image/format.go?s=2676:2730#L82中说我应该传递一个io.Reader作为参数,这就是我正在做的。

英文:

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.

答案1

得分: 12

你的代码有两个问题。

第一个问题是你颠倒了测试条件err != nil,所以你只在出现错误的情况下尝试解码图像。应该是err == nil

第二个问题,正如jimt所说,你在os.Open()中使用了filepath.Name(),它只包含文件名,这导致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("无法打开文件:", err)
        }
    }
}

另外,如果你的目录中有其他图像格式,请不要忘记添加除image/jpeg之外的其他导入项。

英文:

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.

答案2

得分: 3

如果你想在不使用image.DecodeConfig的情况下通过image.Decode(reader)获取图像的宽度和高度,可以使用以下代码:

m, _, err := image.Decode(reader)
if err != nil {
	log.Fatal(err)
}
bounds := m.Bounds()
w := bounds.Dx()
h := bounds.Dy()

fmt.Printf("宽度:%d,高度:%d\n", w, h)

这段代码将读取图像并解码,然后使用Bounds()方法获取图像的边界信息,最后通过Dx()和Dy()方法获取宽度和高度。

英文:

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)

huangapple
  • 本文由 发表于 2014年2月13日 06:39:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/21741431.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定