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

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条回答 默认 最新

相关推荐 更多相似问题