如何使用golang将Microsoft SQL varbinary(max)字段提取到图像?

I have a varbinary(max) field in Microsoft SQL Server which contains an image.

When running "SELECT IMAGE FROM TABLE", I get a result which looks like "0x07FD30...."

When using go to retrieve the data, I get the same hex string which is stored as a []byte:

type Person struct {
    PersonID string
    Image    []byte
} 

I connect to the database and do:

rows.Scan(&person.PersonID, &person.Image)

And then print the result as hex, it's the same:

fmt.Printf("%#x", p.Image)

Result:

0x07fd30...

My question is, how do I turn this back into an image?

I've tried writing the raw bytes to a file:

ioutil.WriteFile("./tempfile.png", p.Image, 0644)

I've tried using the image library to decode it, which just errors with an unidentified kind:

image.Decode(bytes.NewReader(p.Image))

And also tried png.Encode too.

Any thoughts or pointers in the right direction greatly appreciated.

Many thanks in advance.

Writing the raw bytes to a file with ioutil.WriteFile("./tempfile.png", p.Image, 0644) does seem to be the correct process. However, for whatever reason, Microsoft Dynamics AX 2012 seems to add an extra 7 bytes to the beginning of the file when saving it to the database with their BinData class. So, using ioutil.WriteFile(s, p.Image[7:], 0644) works. I'd like to understand what those 7 bytes are and what they're for, but that's for another day. Thanks.

Darren was correct about the first 7 bytes always get added to the image files by AX, that is 07FD3097F90000. Unfortunately, it seems that AX also adds other information to the end of the binary file. I haven't figured out the exact pattern of the that but typically if the uploaded image is .png, AX just adds FF to the end, otherwise it makes tons of changes to the file.

In your case, if you are just interested in one specific image stored in SQL server, take a look at the binary file and see if it's ended with FF. If yes, strip off the extra bytes and then convert it to base64 to display it.

var data="0xFFD8FFE000104A464946....d";

var bytes = [];

for(var i=2; i< data.length-1; i+=2){
    bytes.push(parseInt(data.substr(i, 2), 16));
}
//str contains the base64 form of the image
var str = btoa(String.fromCharCode.apply(String, bytes));