【问题标题】:Get image size with golang使用 golang 获取图像大小
【发布时间】:2022-01-13 22:22:19
【问题描述】:

我是 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("Impossible to open the file")
        }
    }
}

当涉及到image.DecodeConfig 时,我有一个错误,上面写着image: unknown format 有人知道正确的方法吗? 在此处的文档中http://golang.org/src/pkg/image/format.go?s=2676:2730#L82 说我应该将io.Reader 作为参数传递,这就是我正在做的事情。

【问题讨论】:

  • filepath.Name() 只产生文件名。不是它的完整路径。这可能是你的问题。尝试将filepath.Join(dir_to_scan, filepath.Name()) 传递给os.Open()。如果这不是问题,您可能正在尝试读取一些它不理解的奇怪图像格式。

标签: image go


【解决方案1】:

您的代码有两个问题。

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

第二个,正如jimt所说,是你使用filepath.Name(),它只包含os.Open()中的文件名,这就是为什么err总是被设置,因此总是输入@987654326 @,并解码一个不存在的文件。

这是更正后的代码:

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 以外的其他导入。

【讨论】:

  • 啊! err == nil 和图像名称而不是图像路径,真是个白痴!感谢 florent-bayle 和 jimt,它现在可以工作了;)
【解决方案2】:

如果您想通过使用 image.Decode(reader) 而不使用 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)

【讨论】:

    猜你喜欢
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    • 2012-04-15
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    • 2020-03-14
    相关资源
    最近更新 更多