You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.2 KiB

4 years ago
package main
import (
"encoding/base64"
"fmt"
"io/ioutil"
"os"
)
func main() {
// 读取Base64
k := ImagesToBase("D:\\EPWork\\goland\\workspace\\golang_learn\\src\\data_func\\go_to_base64\\rc.ico")
fmt.Print(k)
}
// 图片转Base64
func ImagesToBase64(str_images string) string {
//读原图片
ff, _ := os.Open(str_images)
defer ff.Close()
sourcebuffer := make([]byte, 500000)
n, _ := ff.Read(sourcebuffer)
//base64压缩
return base64.StdEncoding.EncodeToString(sourcebuffer[:n])
}
// 图片转Base64 - 数组
func ImagesToBase(str_images string) []byte {
//读原图片
ff, _ := os.Open(str_images)
defer ff.Close()
sourcebuffer := make([]byte, 500000)
n, _ := ff.Read(sourcebuffer)
sourcestring := base64.StdEncoding.EncodeToString(sourcebuffer[:n])
return []byte(sourcestring)
}
// Base64转图片
func Base64ToImage(sourcestring []byte) {
// 写入临时文件
ioutil.WriteFile("a.png.txt", sourcestring, 0667)
// 读取临时文件
cc, _ := ioutil.ReadFile("a.png.txt")
// 解压
dist, _ := base64.StdEncoding.DecodeString(string(cc))
// 写入新文件
f, _ := os.OpenFile("xx.png", os.O_RDWR|os.O_CREATE, os.ModePerm)
defer f.Close()
f.Write(dist)
return
}