disintegration / imaging

Imaging is a simple image processing package for Go
MIT License
5.3k stars 443 forks source link

Add a `FormatFromExtension` helper #77

Closed oliverpool closed 6 years ago

oliverpool commented 6 years ago

Hi,

first of all, thank for this great package!

  1. I decoded a picture using the stdlib (img, format, err := image.Decode(r)) and I want to save it using the imaging.Encode method.
  2. This method needs the format.
  3. There is a FormatFromFilename helper, which however does not work if fed with the format that I previously got (I currently do imaging.FormatFromFilename("fake." + format)).

I suggest to add the following:

// FormatFromExtension parses image format from extension:
// "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.
func FormatFromExtension(ext string) (Format, error) {
    if f, ok := formatFromExt[strings.ToLower(ext)]; ok {
        return f, nil
    }
    return -1, ErrUnsupportedFormat
}

// FormatFromFilename parses image format from filename extension:
// "jpg" (or "jpeg"), "png", "gif", "tif" (or "tiff") and "bmp" are supported.
func FormatFromFilename(filename string) (Format, error) {
    ext := filepath.Ext(filename)
        return FormatFromExtension(ext)
}
disintegration commented 6 years ago

Hi,

OK, let's add this function. Could you please send a pull request?

I think we should also do strings.TrimPrefix(ext, ".") in addition to strings.ToLower in FormatFromExtension and fix the formatFromExt map, to accept both ".jpeg" and "jpeg".