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

将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条)

报告相同问题?

悬赏问题

  • ¥15 visionmaster启动失败,提示为“机器不满足授权而被禁用”
  • ¥50 用logisim设计16位单时钟周期cpu
  • ¥15 IDEA中圈复杂度如何具体设置
  • ¥50 labview采集不了数据
  • ¥15 请上面代码做什么处理或什么混淆
  • ¥15 英雄联盟自定义房间置顶
  • ¥15 W5500网线插上无反应
  • ¥15 如何用字典的Key,显示在WPF的xaml中
  • ¥15 weautomate读取Excel表格信息然后填写到网页一直报错,如何解决?
  • ¥15 C#如何在Webview2中获取网页验证码