【代码】Go语言实现将Base64编码的图片保存为文件

前言

Go语言实现将Base64编码的图片转换为io.Reader对象最终保存为文件

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main

import (
"bytes"
"encoding/base64"
"io"
"os"
)

func main() {

imageBase64 := ""
filename := "file.jpg"

// 解码 Base64 字符串
imageBytes, _ := base64.StdEncoding.DecodeString(imageBase64)

// 将解码后的字节数组转换为Reader
reader := bytes.NewReader(imageBytes)

// 将图片保存到本地文件
file, _ := os.Create(filename)
defer file.Close()

// 将图片数据写入文件
io.Copy(file, reader)

}

完成