Created
March 7, 2022 21:08
-
-
Save iotku/770ee4d20b366b2f68c2f03c2c117b70 to your computer and use it in GitHub Desktop.
Take a source image (jpg/png) and output a base64 encoded html <img> png
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"encoding/base64" | |
"fmt" | |
"image" | |
_ "image/jpeg" | |
"image/png" | |
"log" | |
"os" | |
"github.com/nfnt/resize" | |
) | |
func main() { | |
resizedImg := resize.Resize(200, 200, decodeImage("source.png"), resize.Lanczos3) | |
var buf bytes.Buffer | |
if err := png.Encode(&buf, resizedImg); err != nil { | |
log.Fatal("Error encoding png for base64", err) | |
} | |
encodedStr := base64.StdEncoding.EncodeToString(buf.Bytes()) | |
fmt.Print("<img src=\"data:image/png;base64, ", encodedStr, "\" />") | |
} | |
func decodeImage(filepath string) image.Image { | |
f, err := os.Open(filepath) | |
if err != nil { | |
log.Fatalf("Failed to open source") | |
} | |
img, _, err := image.Decode(f) | |
if err != nil { | |
log.Fatal("Failed to decode image: ", err) | |
} | |
if err := f.Close(); err != nil { | |
log.Fatal(err) | |
} | |
return img | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment