我正在运行的函数之一: image.Decode()
image.Decode函数接受一个io.Reader &&,io.Reader函数接受一个[]字节。
当我传入一个[]uint8时,if会给我这个错误:
panic: image: unknown format如何将[]uint8转换为[]字节?
更新
错误发生在星形区域,因为image.Decode无法读取变量xxx。
package main
import (
"github.com/nfnt/resize"
"image"
"image/jpeg"
"fmt"
"launchpad.net/goamz/aws"
"launchpad.net/goamz/s3"
"bytes"
"encoding/json"
"io/ioutil"
"os"
"reflect"
)
type Data struct {
Key string
}
func main() {
useast := aws.USEast
connection := s3.New(auth, useast)
mybucket := connection.Bucket("bucketName")
image_data, err := mybucket.Get("1637563605030")
if err != nil {
panic(err.Error())
} else {
fmt.Println("success")
}
xxx := []byte(image_data)
******* THIS IS WHERE THE ERROR OCCURS **************
original_image, _, err := image.Decode(bytes.NewReader(xxx))
******* THIS IS WHERE THE ERROR OCCURS END **************
if err != nil {
fmt.Println("Shit")
panic(err.Error())
} else {
fmt.Println("Another success")
}
new_image := resize.Resize(160, 0, original_image, resize.Lanczos3)
if new_image != nil {
fmt.Println("YAY")
}
}发布于 2014-04-09 09:15:25
The Go Programming Language Specification
Numeric types
uint8 uint8的所有无符号8位整数(0到255)字节别名的集合
package main
import "fmt"
func ByteSlice(b []byte) []byte { return b }
func main() {
b := []byte{0, 1}
u8 := []uint8{2, 3}
fmt.Printf("%T %T\n", b, u8)
fmt.Println(ByteSlice(b))
fmt.Println(ByteSlice(u8))
}输出:
[]uint8 []uint8
[0 1]
[2 3]你误诊了你的问题。
发布于 2014-04-09 09:21:36
正如其他答案所解释的那样,在需要[]byte的地方传递[]uint8是没有问题的。如果这是您的问题,您将得到一个编译时错误。死机是一个运行时错误,它是由image库在读取切片中的数据时抛出的。
事实上,图像库只是你的部分问题。参见http://golang.org/src/pkg/image/format.go。它返回一条错误消息,因为它无法识别切片中数据的图像格式。当image.Decode()返回错误消息时,调用image.Decode()的代码将调用panic。
发布于 2014-04-09 07:59:41
如果您有一个为[]uint8的变量imageData,则可以传递[]byte(imageData)
请参阅http://golang.org/ref/spec#Conversions
https://stackoverflow.com/questions/22950392
复制相似问题