package util import ( "bytes" "fmt" "image" "image/gif" "image/jpeg" "image/png" "io" imaging "github.com/disintegration/imaging" "github.com/nfnt/resize" exif "github.com/rwcarlsen/goexif/exif" "golang.org/x/image/bmp" ) type ContentsCenter struct { TargetWidth int } type rectangle struct { Width int Hegith int } // Support image format list -> "png", "jpeg", "gif", "jpg", func (mc *ContentsCenter) setting() { image.RegisterFormat("jpeg", "jpeg", jpeg.Decode, jpeg.DecodeConfig) image.RegisterFormat("png", "png", png.Decode, png.DecodeConfig) image.RegisterFormat("gif", "gif", gif.Decode, gif.DecodeConfig) image.RegisterFormat("bmp", "bmp", bmp.Decode, bmp.DecodeConfig) mc.TargetWidth = 1440 } func (mc *ContentsCenter) analyzeImage(reader io.Reader) (bool, string, image.Config) { // protected function config, format, err := image.DecodeConfig(reader) if err == nil { return true, format, config } return false, "", image.Config{} } func (mc *ContentsCenter) analyzeVideo() bool { // protected function return false } func (mc *ContentsCenter) Resize(fileData []byte) ([]byte, error) { mc.setting() var c image.Config res := false format := "" axisSwap := false r := bytes.NewReader(fileData) if res, format, c = mc.analyzeImage(io.Reader(r)); !res && !mc.analyzeVideo() { return nil, fmt.Errorf("Unsupported file format") } r = bytes.NewReader(fileData) img, _, err := image.Decode(r) if err != nil { } // rotate if exif's orient value. r = bytes.NewReader(fileData) if _exif, err := exif.Decode(r); err == nil { if exifInfo, err := _exif.Get(exif.Orientation); err != nil { fmt.Errorf(err.Error()) } else { _v := exifInfo.Val[0] if _v == 0 { _v = exifInfo.Val[1] } // fmt.Printf("exifInfo: %d, %d", _v, exifInfo.Val[1]) if _v == 6 { img = imaging.Rotate270(img) axisSwap = true } else if _v == 1 { } else if _v == 8 { img = imaging.Rotate90(img) axisSwap = true } else if _v == 3 { img = imaging.Rotate180(img) } } } else { fmt.Print("Occurred error when decoding!") fmt.Print(err.Error()) } //calculate image ratio var modImg image.Image rY := float32(c.Height) / float32(c.Width) if axisSwap { modImg = resize.Resize( (uint)((float32)(mc.TargetWidth)*rY), (uint)(float32(mc.TargetWidth)), img, resize.Lanczos3) } else { modImg = resize.Resize( (uint)(mc.TargetWidth), (uint)(float32(mc.TargetWidth)*rY), img, resize.Lanczos3) } var buff bytes.Buffer if format == "png" { png.Encode(&buff, modImg) } else if format == "jpeg" || format == "jpg" { jpeg.Encode(&buff, modImg, &jpeg.Options{70}) } else if format == "gif" { gif.Encode(&buff, modImg, &gif.Options{NumColors: 256}) } else if format == "bmp" { png.Encode(&buff, modImg) } return buff.Bytes(), nil }