简体   繁体   English

去base64图像解码

[英]Go base64 image decode

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) 我目前正在从画布上获取像这样的base64图像数据网址(不是dataURL只是为了显示字符串的样子)

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. 所以,是的,我制作dataurl的方式一定是错误的,但无法弄清楚该怎么做。 I also tried passing the full dataurl (with data:image...) still no success 我也尝试传递完整的dataurl(with data:image ...)仍然没有成功

What you have is a Data URI scheme , info on how to decode it and more on this is in this question and answer: 您所拥有的是数据URI方案 ,有关如何对其进行解码的信息以及更多有关此问题的信息,请参见此问答:

Illegal base64 data at input byte 4 when using base64.StdEncoding.DecodeString(str) 使用base64.StdEncoding.DecodeString(str)时,输入字节4处的base64数据非法

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. 但是请注意, image.Decodeconfig()仅会解码在调用此函数之前注册的图像格式,因此您需要预先注册图像格式处理程序。 This can be done with imports like 这可以通过类似的导入来完成

import _ "image/png"

More on this is in the package doc of image . 有关更多信息,请参见image的打包文档。 Or if you know the exact format (eg in your example it's PNG), you can directly use png.DecodeConfig() . 或者,如果您知道确切的格式(例如,在示例中为PNG),则可以直接使用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" ). 因此它对您不起作用,因为您的实际编码图像是PNG格式,但是您没有注册PNG格式处理程序,因此image.DecodeConfig()不会使用PNG处理程序(因此不会能够对其进行解码=> "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. 还要注意,替换不属于Base64编码映像的前缀是解决该问题的较差解决方案。 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. 切片字符串甚至都不会在内存中复制该字符串,它只会创建一个新的(两个单词)字符串标题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM