nfnt / resize

Pure golang image resizing
ISC License
3.02k stars 321 forks source link

Detecting file format #59

Closed mrichman closed 6 years ago

mrichman commented 7 years ago

What's the best way to detect the image file format so I can use the proper decoder?

mikejohanson commented 7 years ago

I had this question too. I tried a couple things.... If you have have the filename, you can do something like this:

isJpeg := strings.HasSuffix(filenameWithEXT, ".jpg") || strings.HasSuffix(filenameWithEXT, ".jpeg")
isPng := fstrings.HasSuffix(filenameWithEXT, ".png")
 if isJpeg {
    img, err = jpeg.Decode(file)
        if err != nil { ... }
}
if isPng {
        img, err = png.Decode(file)
        if err != nil { ... }
}

if you dont have the filename extension you can do something like:

isJpeg := false 
isPng := false  
var img image.Image
var err error
img, err = jpeg.Decode(file)
    if err != nil {
        fmt.Println("ERROR DECODING IMAGE (JPEG). TRYING PNG...")
        img, err = png.Decode(file)
        if err != nil {
            fmt.Println("ERROR DECODING IMAGE (PNG)")
            log.Fatal("No Image or Image Not Supported")
            os.Exit(1)
        } else {
            isPng = true
        }
    } else {
        isJpeg = true
    }

you could easily extend to add .gif support. Not the most elegant solution but it works :) !

mrichman commented 7 years ago

I actually ended up doing this:

func decodeConfig(filename string) (image.Config, string, error) {
    f, err := os.Open(filename)
    if err != nil {
        return image.Config{}, "", err
    }
    defer f.Close()
    return image.DecodeConfig(bufio.NewReader(f))
}

The 2nd return argument (the string) contains the file format (i.e. jpeg, gif, png). Then I just switch on that:

switch format {
    case "jpeg":
        img, err = jpeg.Decode(file)
    case "png":
        img, err = png.Decode(file)
    case "gif":
        img, err = gif.Decode(file)
    default:
        err = errors.New("Unsupported file type")
    }
nfnt commented 6 years ago

Not relevant to this package, closing.