CreateThumb creates a new thumb image for the file at originalKey location. The new thumb file is stored at thumbKey location. thumbSize is in the format: - 0xH (eg. 0x100) - resize to H height preserving the aspect ratio - Wx0 (eg. 300x0) - resize to W width preserving the aspect ratio - W
(originalKey string, thumbKey, thumbSize string)
| 497 | // - WxHb (eg. 300x100b) - resize and crop to WxH viewbox (from bottom) |
| 498 | // - WxHf (eg. 300x100f) - fit inside a WxH viewbox (without cropping) |
| 499 | func (s *System) CreateThumb(originalKey string, thumbKey, thumbSize string) error { |
| 500 | sizeParts := ThumbSizeRegex.FindStringSubmatch(thumbSize) |
| 501 | if len(sizeParts) != 4 { |
| 502 | return errors.New("thumb size must be in WxH, WxHt, WxHb or WxHf format") |
| 503 | } |
| 504 | |
| 505 | width, _ := strconv.Atoi(sizeParts[1]) |
| 506 | height, _ := strconv.Atoi(sizeParts[2]) |
| 507 | resizeType := sizeParts[3] |
| 508 | |
| 509 | if width == 0 && height == 0 { |
| 510 | return errors.New("thumb width and height cannot be zero at the same time") |
| 511 | } |
| 512 | |
| 513 | // fetch the original |
| 514 | r, readErr := s.GetReader(originalKey) |
| 515 | if readErr != nil { |
| 516 | return readErr |
| 517 | } |
| 518 | defer r.Close() |
| 519 | |
| 520 | // create imaging object from the original reader |
| 521 | // (note: only the first frame for animated image formats) |
| 522 | img, decodeErr := imaging.Decode(r, imaging.AutoOrientation(true)) |
| 523 | if decodeErr != nil { |
| 524 | return decodeErr |
| 525 | } |
| 526 | |
| 527 | var thumbImg *image.NRGBA |
| 528 | |
| 529 | if width == 0 || height == 0 { |
| 530 | // force resize preserving aspect ratio |
| 531 | thumbImg = imaging.Resize(img, width, height, imaging.Linear) |
| 532 | } else { |
| 533 | switch resizeType { |
| 534 | case "f": |
| 535 | // fit |
| 536 | thumbImg = imaging.Fit(img, width, height, imaging.Linear) |
| 537 | case "t": |
| 538 | // fill and crop from top |
| 539 | thumbImg = imaging.Fill(img, width, height, imaging.Top, imaging.Linear) |
| 540 | case "b": |
| 541 | // fill and crop from bottom |
| 542 | thumbImg = imaging.Fill(img, width, height, imaging.Bottom, imaging.Linear) |
| 543 | default: |
| 544 | // fill and crop from center |
| 545 | thumbImg = imaging.Fill(img, width, height, imaging.Center, imaging.Linear) |
| 546 | } |
| 547 | } |
| 548 | |
| 549 | originalContentType := r.ContentType() |
| 550 | |
| 551 | opts := &blob.WriterOptions{ |
| 552 | ContentType: originalContentType, |
| 553 | } |
| 554 | |
| 555 | var format imaging.Format |
| 556 |