Getting a multipart.File into image.Decode as argument

Viewed 914

The contents of the multipart.File are as follows: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD..."

I'm trying to get it into the Image.DecodeConfig() method like this:

import (
    "image"
    "image/jpeg"
    "io"
)

func ImgCheckSize(file io.Reader) (io.Reader, error) {
    config, format, err := image.DecodeConfig(file)
...

The error prints: "image: unknown format"

I've also printed out the multipart.FileHeader.Header which reads:

map[Content-Disposition:[form-data; name="img1"; filename="img1"] Content-Type:[application/octet-stream]]

Has anyone come across this before? Any useful suggestions would help! Many many thanks

2 Answers

As it states in the image package’s documentation (https://golang.org/pkg/image/ 92), you have to register the formats that you want to use first:

  • Decoding any particular image format requires the prior registration of a decoder function. Registration is typically automatic as a side effect of initializing that format’s package so that, to decode a PNG image, it suffices to have

  • import _ “image/png”

  • in a program’s main package. The _ means to import a package purely for its initialization side effects.

implementation example: https://play.golang.org/p/7d1gS7_tdc0

import (
    "image"
    // Package image/jpeg is not used explicitly in the code below,
    // but is imported for its initialization side-effect, which allows
    // image.Decode to understand JPEG formatted images. 
    _ "image/jpeg"
    "io"
)

func ImgCheckSize(file io.Reader) (io.Reader, error) {
    config, format, err := image.DecodeConfig(file)
...

Solved with the following package: "github.com/vincent-petithory/dataurl"

for example:

imgdecoded, _ := dataurl.Decode(imgupload)

Related