dongwei4444 2015-10-24 15:21
浏览 109
已采纳

去base64图像解码

Im currently getting a base64 image data url from a canvas something like this (not the dataurl im getting just to show how the string looks like)

data:image/png;base64,iVkhdfjdAjdfirtn=

I need to decode that image to check the width and the height of the image

    dataurl := strings.Replace(req.PostFormValue("dataurl"), "data:image/png;base64,", "", 1)

    reader := base64.NewDecoder(base64.StdEncoding, strings.NewReader(dataurl))
    c, _, err := image.DecodeConfig(reader)
    if err != nil {
        log.Fatal(err)
    }
    log.Println(c.Width)

But Im getting an error while trying to decode the config

Unknown image format

So yeah the way Im making the dataurl must be wrong but cant figure what to do. I also tried passing the full dataurl (with data:image...) still no success

  • 写回答

1条回答 默认 最新

  • duanhuan3012 2015-10-24 18:07
    关注

    What you have is a Data URI scheme, info on how to decode it and more on this is in this question and answer:

    Illegal base64 data at input byte 4 when using base64.StdEncoding.DecodeString(str)

    But note that image.Decodeconfig() will only decode image formats that are registered prior to calling this function, so you need the image format handlers to be registered in advance. This can be done with imports like

    import _ "image/png"
    

    More on this is in the package doc of image. Or if you know the exact format (e.g. in your example it's PNG), you can directly use png.DecodeConfig().

    So it doesn't work for you because your actual encoded image is of PNG format, but you didn't register the the PNG format handler and so image.DecodeConfig() won't use the PNG handler (and so it will not be able to decode it => "Unknown image format").

    Also note that replacing the prefix that is not part of the Base64 encoded image is a poor solution to get rid of it. Instead simply slice the input string:

    input := "data:image/png;base64,iVkhdfjdAjdfirtn="
    b64data := input[strings.IndexByte(input, ',')+1:]
    

    Slicing a string will not even copy the string in memory, it will just create a new (two-word) string header.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 调用函数时,无关变量的改变引起函数值的改变
  • ¥15 xy坐标转化为经纬度坐标
  • ¥15 一般三角模糊数的上界值和下届值取中值的多少比较合理?
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥20 Hbase启动失败,无法启动HMaster
  • ¥15 sqpingboot在父模块已经引入了mybatisplus 在子组件不写版本号还是报错
  • ¥20 Lumerical FDTD solutions 中模型的相对阻抗,有效介电常数和有效磁导率的实部和虚部的数据如何获得?
  • ¥100 sql reporting service 远程smtp服务器配置支持
  • ¥15 ppyoloe_r带角度目标检测,loss_cls没法收敛
  • ¥15 淘宝交易指数如何解读,其关联的数据指标是什么