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) { 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 default: return nil, fmt.Errorf("unsupported format %q: must be webp or jpeg", format) } }