2017-07-14 154 views
1

我嘗試使用內置的「形象」包裝一個PNG圖像,例如:去解碼圖像不支持的類型錯誤

infile, err := os.Open(filename) 
image.RegisterFormat("png", "png", png.Decode, png.DecodeConfig) 
src, _, err := image.Decode(infile) 

image.Decode的功能是生成的unsupported type *image.RGBA錯誤。任何人都有任何洞察到這個錯誤?

我還用JPEG與相應的註冊嘗試這樣做:

image.RegisterFormat("png", "png", png.Decode, png.DecodeConfig) 
src, _, err := image.Decode(infile) 

導致unsupported type *image.YCbCr。非常混亂,因爲圖像本身是RGB。

編輯:也嘗試只是導入image/jpegimage/png,而不使用image.RegisterFormat,但仍然得到相同的錯誤。

編輯#2:道歉,我得到的錯誤甚至不是來自解碼功能。圖像正確解碼。

+0

你是如何生成這些圖像的? –

+0

你使用什麼版本? –

+0

去版本:1.8.3和圖像來自各種數據集,我也試着用谷歌google.com的標誌 –

回答

2

首先錯誤:

註冊格式時,你犯了一個錯誤。

PNG魔術不是"png"而是"\x89PNG\r\n\x1a\n"。所以登記:

image.RegisterFormat("png", "\x89PNG\r\n\x1a\n", png.Decode, png.DecodeConfig) 

的JPEG魔法不是"jpeg""\xff\xd8"。 JPEG註冊:

image.RegisterFormat("jpeg", "\xff\xd8", jpeg.Decode, jpeg.DecodeConfig) 

但是不要這樣做!

只需導入image/pngimage/jpeg程序包,程序包init函數會自動爲您執行此操作。您可以使用blank標識符,如果你不使用包(你只能這樣做的初始化「副作用」):

import (
    _ "image/png" 
    _ "image/jpeg" 
) 

上述進口後,您將能夠PNG解碼和JPEG圖像。

+0

這個答案很奇怪,因爲他的代碼爲我開箱即用,但很高興知道你可以導入包。 –

+0

@BenjaminKadish因爲爲了使'png.Decode'和'png.DecodeConfig'有效,你已經導入了'image/png',並且它的init()函數已經被執行了。 – icza

+0

那爲什麼這不適合他? –

相關問題