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
|
package media
import (
"fmt"
"github.com/davidbyttow/govips/v2/vips"
)
// ConvertAndResize loads the image at src, optionally resizes it to width pixels
// wide (maintaining aspect ratio), and exports it in the requested format.
//
// width <= 0 means no resize. format must be "webp" or "jpeg".
func ConvertAndResize(src string, width int, format string) ([]byte, error) {
if format != "webp" && format != "jpeg" {
return nil, fmt.Errorf("unsupported format %q: must be webp or jpeg", format)
}
img, err := vips.NewImageFromFile(src)
if err != nil {
return nil, fmt.Errorf("load image %s: %w", src, err)
}
defer img.Close()
if width > 0 && width < img.Width() {
scale := float64(width) / float64(img.Width())
if err := img.Resize(scale, vips.KernelLanczos3); err != nil {
return nil, fmt.Errorf("resize: %w", err)
}
}
switch format {
case "webp":
buf, _, err := img.ExportWebp(vips.NewWebpExportParams())
if err != nil {
return nil, fmt.Errorf("export webp: %w", err)
}
return buf, nil
case "jpeg":
buf, _, err := img.ExportJpeg(vips.NewJpegExportParams())
if err != nil {
return nil, fmt.Errorf("export jpeg: %w", err)
}
return buf, nil
}
return nil, fmt.Errorf("unsupported format %q", format)
}
|