我正在运行的一个函数:image.Decode()
image.Decode函数接受io.Reader &&,io.Reader函数接收[]字节.
当我传入[] uint8时,如果给我这个错误:
panic: image: unknown format
Run Code Online (Sandbox Code Playgroud)
如何将[] uint8转换为[]字节?
UPDATE错误发生在星号区域,因为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")
}
}
Run Code Online (Sandbox Code Playgroud)
pet*_*rSO 44
Run Code Online (Sandbox Code Playgroud)uint8 the set of all unsigned 8-bit integers (0 to 255) byte alias for uint8
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))
}
Run Code Online (Sandbox Code Playgroud)
输出:
[]uint8 []uint8
[0 1]
[2 3]
Run Code Online (Sandbox Code Playgroud)
你错误地诊断了你的问题.
正如其他答案所解释的那样,传递a 所需的[]uint8位置没有问题[]byte.如果这是您的问题,您将收到编译时错误.你不是.恐慌是运行时错误,当它读取切片中的数据时,它会被图像库抛出.
实际上,图像库只是部分问题.请参阅http://golang.org/src/pkg/image/format.go.它返回一条错误消息,因为它无法识别切片中数据的图像格式.您的代码,在返回错误消息时调用image.Decode()它.panicimage.Decode()
Dan*_*ams -1
如果你有一个变量imageData,[]uint8你可以通过[]byte(imageData)
请参阅http://golang.org/ref/spec#Conversions