使用golang获取图像大小
发布时间:2020-12-16 09:25:59 所属栏目:大数据 来源:网络整理
导读:我是golang的新手,我正在尝试获取目录中列出的所有图像的图像大小.这就是我所做的 package mainimport ( "fmt" "image" _ "image/jpeg" "io/ioutil" "os")const dir_to_scan string = "/home/da/to_merge"func main() { files,_ := ioutil.ReadDir(dir_to_sc
|
我是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: %vn",filepath.Name(),err)
continue
}
fmt.Printf("%s %d %dn",im.Width,im.Height)
} else {
fmt.Println("Impossible to open the file")
}
}
}
我对image.DecodeConfig有一个错误,即图像:未知格式 解决方法
您的代码有两个问题.
第一个是您已经将测试错误!= 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,imgFile := range files {
if reader,err := os.Open(filepath.Join(dir_to_scan,imgFile.Name())); err == nil {
defer reader.Close()
im,imgFile.Name(),im.Height)
} else {
fmt.Println("Impossible to open the file:",err)
}
}
}
此外,如果您的目录中有其他图像格式,请不要忘记添加除image / jpeg之外的其他导入. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
