doubihuai8468
2017-02-10 07:59
浏览 278
已采纳

如何使用golang在文件系统中的base64字符串中创建jpg / png图像

I am sending base64 string from Rest call to Golang server using Angular.Now the problem is to create image using this string.

My code :

func (server *Server) uploadImage(w http.ResponseWriter, r *http.Request) {

    decoder := json.NewDecoder(r.Body)
    defer r.Body.Close()
    var d model.ImageFile
    err := decoder.Decode(&d)
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }
    fmt.Println(d.Source)
    fmt.Println(d.Destination)
    fmt.Println(d.Country)

    dir, errr := filepath.Abs(filepath.Dir(os.Args[0]))
    if errr != nil {
        fmt.Println(errr)
    }
    substring := dir[0:(len(dir) - 10)]

    unbased, err := base64.StdEncoding.DecodeString(d.ImageData)
    if err != nil {
        fmt.Println("Cannot decode b64")
    }

    r = bytes.NewReader(unbased)
    im, err := png.Decode(r)
    if err != nil {
        fmt.Println("Bad png")
    }

    f, err := os.OpenFile(substring+"images/"+"example.png", os.O_WRONLY|os.O_CREATE, 777)
    if err != nil {
        fmt.Println("Cannot open file")
    }

    png.Encode(f, im)

    server.R.Text(w, http.StatusOK, d.ID.Hex())
    return
}
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dougou8573 2017-02-10 08:27
    已采纳

    I would do something like this :

    b := getB64PNG()
    unbased, err := base64.StdEncoding.DecodeString(b)
    if err != nil {
        panic("Cannot decode b64")
    }
    
    r := bytes.NewReader(unbased)
    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)
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题