doumi0737 2016-07-28 23:57
浏览 597
已采纳

Go-将base64字符串保存到文件

so.. I have a base64 encoded string which I need to decode, check it's width and height and then save to file. However.. I've consistently been getting a corrupt image file saved.

package server

import (
    "encoding/base64"
    "errors"
    "io"
    "os"
    "strings"

    "image"
    _ "image/gif"
    _ "image/jpeg"
    _ "image/png"
)

var (
    ErrBucket       = errors.New("Invalid bucket!")
    ErrSize         = errors.New("Invalid size!")
    ErrInvalidImage = errors.New("Invalid image!")
)

func saveImageToDisk(fileNameBase, data, bucket string) (string, error) {
    idx := strings.Index(data, ";base64,")
    if idx < 0 {
        return "", ErrInvalidImage
    }

    reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data[idx+8:]))
    imgCfg, fmt, err := image.DecodeConfig(reader)
    if err != nil {
        return "", err
    }

    if imgCfg.Width != 750 || imgCfg.Height != 685 {
        return "", ErrSize
    }

    fileName := fileNameBase + "." + fmt
    f, err := os.Create(fileName)
    if err != nil {
        return "", err
    }

    _, err = io.Copy(f, reader)
    f.Close()

    return fileName, err
}

It does save A file.. and the base64 I'm testing with is valid as per online base64 to image converters. Any help?

http://pastebin.com/u18eRv7d Here's the base64 string i'm using (data in the func)

  • 写回答

2条回答 默认 最新

  • douyimin1083 2016-07-29 02:53
    关注

    The main problem of those code is, when you read the io.Reader, the cursor won't back to the first. And you already read the io.Reader on the on decoding image config. So when you write it to file, it will read next until EOF (which maybe not your data)

    I don't know exactly how to reset the io.Reader back to first but I write a work around way to make it work :

    import (
        "encoding/base64"
        "errors"
        "strings"
    
        "image"
        _ "image/gif"
        _ "image/jpeg"
        _ "image/png"
        "io/ioutil"
        "bytes"
    )
    
    var (
        ErrBucket       = errors.New("Invalid bucket!")
        ErrSize         = errors.New("Invalid size!")
        ErrInvalidImage = errors.New("Invalid image!")
    )
    
    func saveImageToDisk(fileNameBase, data string) (string, error) {
        idx := strings.Index(data, ";base64,")
        if idx < 0 {
            return "", ErrInvalidImage
        }
        reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(data[idx+8:]))
        buff := bytes.Buffer{}
        _, err := buff.ReadFrom(reader)
        if err != nil {
            return "", err
        }
        imgCfg, fm, err := image.DecodeConfig(bytes.NewReader(buff.Bytes()))
        if err != nil {
            return "", err
        }
    
        if imgCfg.Width != 750 || imgCfg.Height != 685 {
            return "", ErrSize
        }
    
        fileName := fileNameBase + "." + fm
        ioutil.WriteFile(fileName, buff.Bytes(), 0644)
    
        return fileName, err
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效