github.com/0chain/gosdk@v1.17.11/core/imageutil/thumbnailer.go (about)

     1  // Provides helper methods and data structures to work with images.
     2  package imageutil
     3  
     4  import (
     5  	"bytes"
     6  	"fmt"
     7  	"image"
     8  	_ "image/gif"
     9  	_ "image/jpeg"
    10  	"image/png"
    11  	_ "image/png"
    12  
    13  	_ "golang.org/x/image/bmp"
    14  	_ "golang.org/x/image/ccitt"
    15  	_ "golang.org/x/image/riff"
    16  	_ "golang.org/x/image/tiff"
    17  	_ "golang.org/x/image/vector"
    18  	_ "golang.org/x/image/vp8"
    19  	_ "golang.org/x/image/vp8l"
    20  	_ "golang.org/x/image/webp"
    21  )
    22  
    23  type SubImager interface {
    24  	SubImage(r image.Rectangle) image.Image
    25  }
    26  
    27  // CreateThumbnail create thumbnail of an image buffer. It supports
    28  //   - png
    29  //   - jpeg
    30  //   - gif
    31  //   - bmp
    32  //   - ccitt
    33  //   - riff
    34  //   - tiff
    35  //   - vector
    36  //   - vp8
    37  //   - vp8l
    38  //   - webp
    39  func CreateThumbnail(buf []byte, width, height int) ([]byte, error) {
    40  	// image.Decode requires that you import the right image package.
    41  	// Ignored return value is image format name.
    42  	img, _, err := image.Decode(bytes.NewReader(buf))
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  
    47  	// I've hard-coded a crop rectangle, start (0,0), end (100, 100).
    48  	img, err = cropImage(img, image.Rect(0, 0, width, height))
    49  	if err != nil {
    50  		return nil, err
    51  	}
    52  
    53  	fd := &bytes.Buffer{}
    54  
    55  	err = png.Encode(fd, img)
    56  	if err != nil {
    57  		return nil, err
    58  	}
    59  
    60  	return fd.Bytes(), nil
    61  }
    62  
    63  // cropImage takes an image and crops it to the specified rectangle.
    64  func cropImage(img image.Image, crop image.Rectangle) (image.Image, error) {
    65  
    66  	// img is an Image interface. This checks if the underlying value has a
    67  	// method called SubImage. If it does, then we can use SubImage to crop the
    68  	// image.
    69  	simg, ok := img.(SubImager)
    70  	if !ok {
    71  		return nil, fmt.Errorf("image does not support cropping")
    72  	}
    73  
    74  	return simg.SubImage(crop), nil
    75  }