• 支持不同格式之间的转换
  • 支持图片像素的压缩以及拉长
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package main

import (
	"bytes"
	"errors"
	"fmt"
	"image"
	"image/jpeg"
	"image/png"
	"io/ioutil"
	"os"

	"golang.org/x/image/draw"
	_ "golang.org/x/image/webp" // for RegisterFormat
)

type imageHelper struct {
	img      image.Image
	fileName string
	format   string
	scale    draw.Scaler
}

func NewImageHelper(fileName string, scale ...draw.Scaler) *imageHelper {
	var s draw.Scaler
	if scale == nil {
		s = draw.ApproxBiLinear
	} else {
		s = scale[0]
	}
	return &imageHelper{
		fileName: fileName,
		scale:    s,
	}
}

func (r *imageHelper) GuessFileFormat() (string, error) {
	if r.format != "" && r.img != nil {
		return r.format, nil
	}
	f, err := os.Open(r.fileName)
	if err != nil {
		return "", err
	}
	_image, s, err := image.Decode(f)
	if err != nil {
		return "", err
	}
	r.img = _image
	r.format = s

	ss := _image.Bounds()
	fmt.Println(ss)
	return s, nil
}

func (r *imageHelper) SaveAs(format string) (*bytes.Buffer, error) {
	_, err := r.GuessFileFormat()
	if err != nil {
		return nil, err
	}
	buf := bytes.Buffer{}
	switch format {
	case "jpeg", "jpg":
		err := jpeg.Encode(&buf, r.img, &jpeg.Options{Quality: 100})
		if err != nil {
			return nil, err
		}
		return &buf, nil
	case "png":
		err := png.Encode(&buf, r.img)
		if err != nil {
			return nil, err
		}
		return &buf, nil
	default:
		return nil, errors.New("invalid format")
	}
}

func (r *imageHelper) SaveAsJpeg() (*bytes.Buffer, error) {
	return r.SaveAs("jpeg")
}

func (r *imageHelper) GetSize() (int, int) {
	point := r.img.Bounds().Size()
	return point.X, point.Y
}

func (r *imageHelper) RestSize(x, y int) ([]byte, error) {
	// https://github.com/nfnt/resize/blob/master/resize_test.go
	rect := image.Rect(0, 0, x, y)
	// new img
	dst := image.NewRGBA(rect)
	buf := bytes.Buffer{}
	r.scale.Scale(dst, rect, r.img, r.img.Bounds(), draw.Over, nil)
	err := jpeg.Encode(&buf, dst, &jpeg.Options{Quality: 100})
	if err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

func main() {
	obj := NewImageHelper("webp/1.webp")
	buf, err := obj.SaveAs("png")
	if err != nil {
		return
	}
	ioutil.WriteFile("test1.png", buf.Bytes(), 0644)

	buf, err = obj.SaveAs("jpeg")
	if err != nil {
		return
	}
	ioutil.WriteFile("test2.jpeg", buf.Bytes(), 0644)

	content, _ := obj.RestSize(200, 100)
	ioutil.WriteFile("test3.jpeg", content, 0644)
}