github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zstring/encoding.go (about) 1 package zstring 2 3 import ( 4 "bytes" 5 "encoding/base64" 6 "encoding/gob" 7 "fmt" 8 "io/ioutil" 9 "path/filepath" 10 "strings" 11 12 "github.com/sohaha/zlsgo/zfile" 13 ) 14 15 func Base64Encode(value []byte) []byte { 16 dst := make([]byte, base64.StdEncoding.EncodedLen(len(value))) 17 base64.StdEncoding.Encode(dst, value) 18 return dst 19 } 20 21 func Base64EncodeString(value string) string { 22 data := String2Bytes(value) 23 return base64.StdEncoding.EncodeToString(data) 24 } 25 26 func Base64Decode(data []byte) (value []byte, err error) { 27 src := make([]byte, base64.StdEncoding.DecodedLen(len(data))) 28 n, err := base64.StdEncoding.Decode(src, data) 29 return src[:n], err 30 } 31 32 func Base64DecodeString(data string) (value string, err error) { 33 var dst []byte 34 dst, err = base64.StdEncoding.DecodeString(data) 35 if err == nil { 36 value = Bytes2String(dst) 37 } 38 return 39 } 40 41 func Serialize(value interface{}) ([]byte, error) { 42 buf := bytes.Buffer{} 43 enc := gob.NewEncoder(&buf) 44 gob.Register(value) 45 46 err := enc.Encode(&value) 47 if err != nil { 48 return nil, err 49 } 50 51 return buf.Bytes(), nil 52 } 53 54 func UnSerialize(valueBytes []byte, registers ...interface{}) (value interface{}, err error) { 55 for _, v := range registers { 56 gob.Register(v) 57 } 58 buf := bytes.NewBuffer(valueBytes) 59 dec := gob.NewDecoder(buf) 60 err = dec.Decode(&value) 61 return 62 } 63 64 // Img2Base64 read picture files and convert to base 64 strings 65 func Img2Base64(path string) (string, error) { 66 path = zfile.RealPath(path) 67 imgType := "jpg" 68 ext := filepath.Ext(path) 69 if ext != "" { 70 imgType = imgType[1:] 71 } 72 imgBuffer, err := ioutil.ReadFile(path) 73 if err != nil { 74 return "", err 75 } 76 imgType = strings.ToLower(imgType) 77 return fmt.Sprintf("data:image/%s;base64,%s", imgType, Bytes2String(Base64Encode(imgBuffer))), nil 78 }