TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to GO

Golang base64 Encoding Example: EncodeToString

Use the encoding base64 package and calls EncodeToString. Convert a JPG image to base64.
Base64. Sometimes we want to convert images to text (by using their base64 encoding) for web pages. This can reduce requests and make things go faster.
With the encoding/base64 package, we can use the EncodeToString func in Go to get a string from a byte slice containing the image. We can then create a data URI for our image.Bytes
An example. Here we have a "coin.jpg" image in the home directory. You will want to modify the path to the location of an image that exists.

Then: We use the os package (and the Open method) and the bufio package to read in all the image's bytes.

File

Finally: We invoke base64.StdEncoding.EncodeToString to get a string from our byte slice. This is a base64 string.

Strings
Golang program that uses base64 encoding, EncodeToString package main import ( "bufio" "encoding/base64" "fmt" "io/ioutil" "os" ) func main() { // Open file on disk. f, _ := os.Open("./coin.jpg") // Read entire JPG into byte slice. reader := bufio.NewReader(f) content, _ := ioutil.ReadAll(reader) // Encode as base64. encoded := base64.StdEncoding.EncodeToString(content) // Print encoded data to console. // ... The base64 image can be used as a data URI in a browser. fmt.Println("ENCODED: " + encoded) } Output ENCODED: /9j/2wBDAAQDAwQDAwQEAwQFBAQFBgoHBgYGBg0JCgg [truncated]
Notes, program output. We truncate the output of the program, as the image is too large to be easily displayed. I verified (using an online tool) that the base64 representation is correct.
A summary. With base64, we can store images as text in an ASCII text file. This has advantages and disadvantages—too many to list here. But base64 is often useful in programming.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf