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

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 修改中兴光猫sn的时候提示失败
  • ¥15 java大作业爬取网页
  • ¥15 怎么获取欧易的btc永续合约和交割合约的5m级的历史数据用来回测套利策略?
  • ¥15 有没有办法利用libusb读取usb设备数据
  • ¥15 为什么openeluer里面按不了python3呢?
  • ¥15 关于#matlab#的问题:训练序列与输入层维度不一样
  • ¥15 关于Ubuntu20.04.3LTS遇到的问题:在安装完CUDA驱动后,电脑会进入卡死的情况,但可以通过键盘按键进入安全重启,但重启完又会进入该情况!
  • ¥15 关于#嵌入式硬件#的问题:树莓派第一天重装配置python和opencv后第二天打开就成这样,瞎捣鼓搞出来文件夹还是没把原来的界面调回来
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥20 Arduino 循迹小车程序电路出错故障求解