nfnt / resize

Pure golang image resizing

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Detecting file format

mrichman opened this issue · comments

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

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 :) !

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")
	}

Not relevant to this package, closing.