Golang : Convert an image file to []byte
This is a quick tutorial on how to convert an image file to byte array. This question was originally posted to me via email at admin@socketloop.com by Mr. Aung.
Basically, Mr. Aung would like to know how to turn an image file into a byte array ( []byte )
and the answer is :
fileToBeUploaded := "image.jpg"
file, err := os.Open(fileToBeUploaded)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer file.Close()
fileInfo, _ := file.Stat()
var size int64 = fileInfo.Size()
bytes := make([]byte, size)
// read file into bytes
buffer := bufio.NewReader(file)
_, err = buffer.Read(bytes) // <--------------- here!
// then we need to determine the file type
// see https://www.socketloop.com/tutorials/golang-how-to-verify-uploaded-file-is-image-or-allowed-file-types
filetype := http.DetectContentType(bytes)
err = bucket.Put(path, bytes, filetype, s3.ACL("public-read"))
the code fragment is taken from https://www.socketloop.com/tutorials/golang-upload-and-download-file-to-from-aws-s3
See also : Golang : Upload and download file to/from AWS S3
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.3k SSL : How to check if current certificate is sha1 or sha2 from command line
+10k Golang : Capture stdout of a child process and act according to the result
+1k Golang : How to check if a website is served via HTTPS
+17.7k Golang : Call function from another package
+3.9k Golang : Gorilla web tool kit schema example
+3.7k Golang : Handle sub domain with Gin
+6.5k Golang: Pad right or print ending(suffix) zero or spaces in fmt.Printf example
+15.6k Golang : Setting up/configure AWS credentials with official aws-sdk-go
+3.1k Golang : Detect sample rate, channels or latency with PortAudio
+5.3k Golang : Copy map(hash table) example
+10.7k Golang : Fix cannot download, $GOPATH not set error
+1.3k Golang & Javascript : How to save cropped image to file on server