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
+4k Google : Block or disable caching of your website content
+25.4k PHP : Convert(cast) string to bigInt
+4.4k Golang : Reclaim memory occupied by make() example
+9.2k Golang : How to get quoted string into another string?
+8.9k Golang : Convert octal value to string to deal with leading zero problem
+7.8k Golang : GMail API create and send draft with simple upload attachment example
+7.9k Golang : How to extract video or image files from html source code
+17.7k Golang : convert int to string
+17.4k Golang : Set, Get and List environment variables
+22.8k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+4.3k Golang : Issue HTTP commands to server and port example
+5.3k PHP : Proper way to get UTF-8 character or string length