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

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
    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
    }
    
    点赞 评论
  • drw85135
    drw85135 2017-12-30 00:34

    The other answer didn't work for me, and I wanted to be able to save images as a file regardless of the image format:

    package main
    
    import (
        "bytes"
        "encoding/base64"
        "image/gif"
        "image/jpeg"
        "image/png"
        "log"
        "os"
        "strings"
    
        _ "github.com/jinzhu/gorm/dialects/postgres"
    )
    
    const data = `data:image/gif;base64,R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX/+MjMUcAN8zM/9wcM8ZGcATEL+QePdZWf/29uc/P9cmJu9MTDImIN+/r7+/vz8/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNSUnNWSMQ5MBAQEJE3QPIGAM9AQMqGcG9vb6MhJsEdGM8vLx8fH98AANIWAMuQeL8fABkTEPPQ0OM5OSYdGFl5jo+Pj/+pqcsTE78wMFNGQLYmID4dGPvd3UBAQJmTkP+8vH9QUK+vr8ZWSHpzcJMmILdwcLOGcHRQUHxwcK9PT9DQ0O/v70w5MLypoG8wKOuwsP/g4P/Q0IcwKEswKMl8aJ9fX2xj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ckZ98xoICbTcIJGQAZcNmdmUc210hs35nCyJ58fgmIKX5RQGOZowxaZwYA+JaoKQwswGijBV4C6SiTUmpphMspJx9unX4KaimjDv9aaXOEBteBqmuuxgEHoLX6Kqx+yXqqBANsgCtit4FWQAEkrNbpq7HSOmtwag5w57GrmlJBASEU18ADjUYb3ADTinIttsgSB1oJFfA63bduimuqKB1keqwUhoCSK374wbujvOSu4QG6UvxBRydcpKsav++Ca6G8A6Pr1x2kVMyHwsVxUALDq/krnrhPSOzXG1lUTIoffqGR7Goi2MAxbv6O2kEG56I7CSlRsEFKFVyovDJoIRTg7sugNRDGqCJzJgcKE0ywc0ELm6KBCCJo8DIPFeCWNGcyqNFE06ToAfV0HBRgxsvLThHn1oddQMrXj5DyAQgjEHSAJMWZwS3HPxT/QMbabI/iBCliMLEJKX2EEkomBAUCxRi42VDADxyTYDVogV+wSChqmKxEKCDAYFDFj4OmwbY7bDGdBhtrnTQYOigeChUmc1K3QTnAUfEgGFgAWt88hKA6aCRIXhxnQ1yg3BCayK44EWdkUQcBByEQChFXfCB776aQsG0BIlQgQgE8qO26X1h8cEUep8ngRBnOy74E9QgRgEAC8SvOfQkh7FDBDmS43PmGoIiKUUEGkMEC/PJHgxw0xH74yx/3XnaYRJgMB8obxQW6kL9QYEJ0FIFgByfIL7/IQAlvQwEpnAC7DtLNJCKUoO/w45c44GwCXiAFB/OXAATQryUxdN4LfFiwgjCNYg+kYMIEFkCKDs6PKAIJouyGWMS1FSKJOMRB/BoIxYJIUXFUxNwoIkEKPAgCBZSQHQ1A2EWDfDEUVLyADj5AChSIQW6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw==`
    
    func main() {
        idx := strings.Index(data, ";base64,")
        if idx < 0 {
            panic("InvalidImage")
        }
        ImageType := data[11:idx]
        log.Println(ImageType)
    
        unbased, err := base64.StdEncoding.DecodeString(data[idx+8:])
        if err != nil {
            panic("Cannot decode b64")
        }
        r := bytes.NewReader(unbased)
        switch ImageType {
        case "png":
            im, err := png.Decode(r)
            if err != nil {
                panic("Bad png")
            }
    
            f, err := os.OpenFile("example.png", os.O_WRONLY|os.O_CREATE, 0777)
            if err != nil {
                panic("Cannot open file")
            }
    
            png.Encode(f, im)
        case "jpeg":
            im, err := jpeg.Decode(r)
            if err != nil {
                panic("Bad jpeg")
            }
    
            f, err := os.OpenFile("example.jpeg", os.O_WRONLY|os.O_CREATE, 0777)
            if err != nil {
                panic("Cannot open file")
            }
    
            jpeg.Encode(f, im, nil)
        case "gif":
            im, err := gif.Decode(r)
            if err != nil {
                panic("Bad gif")
            }
    
            f, err := os.OpenFile("example.gif", os.O_WRONLY|os.O_CREATE, 0777)
            if err != nil {
                panic("Cannot open file")
            }
    
            gif.Encode(f, im, nil)
        }
    }
    

    this supports png, gif, and jpeg.

    点赞 评论

相关推荐