dougou1943 2017-09-03 10:02
浏览 159
已采纳

将base64字符串转换为JPG

I am getting the image as base64 string ( dataurl ) , Below is my function that converts the dataurl into the image,

Now if images is png than png library will create the image and jpg library will throw error and vise versa.

Problem is when i upload png it works well but when i upload jpg file
returns this error

invalid JPEG format: missing SOI marker

func (ProfileController) SetProfilePic(w http.ResponseWriter, r *http.Request) {

    session, _ := session.UserSession.Get(r, "mvc-user-session")

    var fieldMapForBasic map[string]*json.RawMessage
    var f *os.File

    data, _ := ioutil.ReadAll(r.Body)
    json.Unmarshal(data, &fieldMapForBasic)

    image, _ := json.Marshal(fieldMapForBasic["image"])
    coI := strings.Index(string(image), ",")
    rawImage := string(image)[coI+1:]

     // Encoded Image DataUrl //
    unbased, _ := base64.StdEncoding.DecodeString(string(rawImage))

    res := bytes.NewReader(unbased)
    path , _ := os.Getwd()


     // Path to store the image //
    newpath := filepath.Join( path +  "/storage",  strconv.Itoa(session.Values["id"].(int) ))
    os.MkdirAll(newpath, os.ModePerm)
    uid := uuid.NewV4()
    fmt.Println(newpath)

    // if image is png this function will create the image from dataurl string//
    pngI, errPng := png.Decode(res)
    if  errPng == nil {
        f, _ = os.OpenFile(newpath + "/" + uid.String() + ".png", os.O_WRONLY | os.O_CREATE, 0777)
        png.Encode(f, pngI)
        fmt.Println("Png generated")
        user := model.User{}
        user.ProfilePic = "storage/"+ strconv.Itoa(session.Values["id"].(int) ) + "/" + uid.String()
        session.Values["profile_pic"] = user.ProfilePic
        session.Save(r,w)
        database.Connection.Id(session.Values["id"].(int)).Update(&user)
    }else{
        fmt.Println(errPng.Error())
    }


    // If image is Jpg this will generate the Image //
    jpgI, errJpg := jpeg.Decode(res)
    if errJpg == nil {
        f, _ = os.OpenFile(newpath + "/" + uid.String() + ".jpg", os.O_WRONLY | os.O_CREATE, 0777)
        jpeg.Encode(f, jpgI, &jpeg.Options{Quality:75})
        fmt.Println("Jpg created")
    }else {
        fmt.Println(errJpg.Error())
    }


    defer func() {
        f.Close()
    }()


    render.Json(w, "ok")
}

Input dataurl is :

"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCADeAN4DASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDtKKKK/cD8rCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/Z"

This might help

  • 写回答

2条回答 默认 最新

  • duanjiaolia97750 2017-09-06 14:51
    关注

    You're passing your io.Reader to png.Decode(), which begins consuming the reader, only to discover that the input is not a valid PNG, so returns an error.

    Then your partly-consumed reader is passed to jpeg.Decode(), which reads the data not yet read, which is not a valid JPEG, and returns the error you observe.

    You need to create a new reader for each decoder:

    pngI, errPng := png.Decode(bytes.NewReader(unbased))
    
    // ...
    
    jpgI, errJpg := jpeg.Decode(bytes.NewReader(unbased))
    

    Or better yet, consider the MIME type, and only call the proper decoder:

    switch strings.TrimSuffix(image[5:coI], ";base64") {
    case "image/png":
        pngI, err = png.Decode(res)
        // ...
    case "image/jpeg":
        jpgI, err = jpeg.Decode(res)
        // ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 同步两个不同结果的array中某些属性
  • ¥15 悬赏15远程操控解决问题
  • ¥15 CST复制的模型无法单独修改参数?
  • ¥15 前端页面想做个定时任务,但是使用requestAnimationFrame,setinterval和settimeout都不行
  • ¥15 根据以下文字信息,做EA模型图
  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热