英文:
image.Decode fail on golang embed
问题
这个程序的目的是解码一个嵌入了"embed"的图像。
图像(bu.png
)位于main.go的相同目录中。
- 看起来嵌入的方式未能设置完全相同的资源
package main
import (
"bytes"
_ "embed"
"image"
)
var (
//go:embed bu.png
img []byte
)
func main() {
a := bytes.NewBuffer(img)
a, b, e := image.Decode()
println(e.Error())
// image: unknown format
println(b)
//
println(a)
// (0x0,0x0)
// println(string(img))
// the text of the image seem a little different between nano
}
图像数据应该在img变量中,因为导入了"embed"。
英文:
The purpose of this program in to decode a img embedded with "embed".
The image (bu.png
) is in the same directory of the main.go.
- It seem that the embed way fail to set the exact same resources
package main
import (
"bytes"
_ "embed"
"image"
)
var (
//go:embed bu.png
img []byte
)
func main() {
a := bytes.NewBuffer(img)
a, b, e := image.Decode()
println(e.Error())
// image: unknown format
println(b)
//
println(a)
// (0x0,0x0)
// println(string(img))
// the text of the image seem a little different between nano
}
the image data shold be in the img variabile cause "embed" import
答案1
得分: 7
这不是一个embed
的问题。你需要导入你想要支持的各个库。它们的初始化将注册它们的格式以供image.Decode
使用。引用上面链接中的话:
> 解码任何特定的图像格式需要先注册一个解码器函数。
尝试添加如下导入语句:
_ "image/png"
我使用以下代码进行了测试,这应该能让你相信embed
是无关紧要的:
package main
import (
_ "embed"
"fmt"
"bytes"
"image"
//_ "image/png"
//_ "image/jpeg"
//_ "image/gif"
"os"
)
var (
//go:embed bu.png
img []byte
)
func main() {
f, err := os.Open("bu.png")
if err != nil {
panic(fmt.Errorf("Couldn't open file: %w", err))
}
defer f.Close()
fmt.Println(image.Decode(f))
buf := bytes.NewBuffer(img)
fmt.Println(image.Decode(buf))
}
英文:
This isn't an embed
thing. You have to import the individual libraries you want to support. Their initialization will register their formats for use by image.Decode
. To quote the aforelinked,
> Decoding any particular image format requires the prior registration of a decoder function.
Try adding an import like,
_ "image/png"
I tested this with the following, which should convince you that embed
is irrelevant:
package main
import (
_ "embed"
"fmt"
"bytes"
"image"
//_ "image/png"
//_ "image/jpeg"
//_ "image/gif"
"os"
)
var (
//go:embed bu.png
img []byte
)
func main() {
f, err := os.Open("bu.png")
if err != nil {
panic(fmt.Errorf("Couldn't open file: %w", err))
}
defer f.Close()
fmt.Println(image.Decode(f))
buf := bytes.NewBuffer(img)
fmt.Println(image.Decode(buf))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论