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
+21.2k Golang : Convert(cast) string to rune and back to string example
+5.4k Javascript : How to loop over and parse JSON data?
+5.2k Golang : PGX CopyFrom to insert rows into Postgres database
+17.2k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+6.8k Golang : Join lines with certain suffix symbol example
+6k PHP : How to check if an array is empty ?
+29.1k Golang : Get first few and last few characters from string
+13.6k Golang : Query string with space symbol %20 in between
+16.3k Golang :Trim white spaces from a string
+22.2k Golang : Convert seconds to minutes and remainder seconds
+10.2k Golang : Bcrypting password
+8.9k Golang : Gaussian blur on image and camera video feed examples