image.Decode在golang embed上失败了。

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

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))

}

huangapple
  • 本文由 发表于 2021年11月2日 05:56:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/69803193.html
匿名

发表评论

匿名网友

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

确定