基本操作

读取和导出图片

我们以 Go 为例,在安装了 govips 之后,可以使用以下代码进行基本图像操作:

package main

import (
	"github.com/davidbyttow/govips/v2/vips"
	"os"
)

func main() {
	vips.Startup(nil)
	defer vips.Shutdown()

	img, err := vips.NewImageFromFile("input.jpg")
	if err != nil {
		panic(err)
	}
	imageBytes, _, _ := img.ExportPng(vips.NewPngExportParams())
	_ = os.WriteFile("output.jpg", imageBytes, 0644)
}
Python 代码案例,点这里
import pyvips

image = pyvips.Image.new_from_file('some-image.jpg', access='sequential')
image *= [1, 2, 1]
mask = pyvips.Image.new_from_list([[-1, -1, -1],
                                   [-1, 16, -1],
                                   [-1, -1, -1]
                                  ], scale=8)
image = image.conv(mask, precision='integer')
image.write_to_file('x.jpg')
Javascript 代码案例,点这里
const sharp = require('sharp');
sharp('input.jpg')
  .rotate()
  .resize(200)
  .jpeg({ mozjpeg: true })
  .toBuffer()
  .then( data => { ... })
  .catch( err => { ... });

这里 img 会是一个 ImageRef 对象,后续的所有操作都是围绕这个对象来的,所以后文中所有的操作都假设你已经有了一个 ImageRef 对象,名字为 img

// ImageRef contains a libvips image and manages its lifecycle.
type ImageRef struct {
	// NOTE: We keep a reference to this so that the input buffer is
	// never garbage collected during processing. Some image loaders use random
	// access transcoding and therefore need the original buffer to be in memory.
	buf                 []byte
	image               *C.VipsImage
	format              ImageType
	originalFormat      ImageType
	lock                sync.Mutex
	preMultiplication   *PreMultiplicationState
	optimizedIccProfile string
}

转换图片格式

例如,如果我们希望将图片从 jpg 格式转换成 webp 格式,和我们的 WebP Server Go 项目一样,我们可以使用以下代码:

package main

import (
	"os"

	"github.com/davidbyttow/govips/v2/vips"
)

func main() {
	vips.Startup(nil)
	defer vips.Shutdown()

	img, err := vips.NewImageFromFile("input.jpg")
	if err != nil {
		panic(err)
	}
	imageBytes, _, _ := img.ExportWebp(vips.NewWebpExportParams())
	os.WriteFile("output.webp", imageBytes, 0644)
}

其中 vips.NewWebpExportParams() 会生成一个默认的 webp 导出参数,你可以根据需要进行调整,可调参数如下:

// WebpExportParams are options when exporting a WEBP to file or buffer
type WebpExportParams struct {
	StripMetadata   bool
	Quality         int
	Lossless        bool
	NearLossless    bool
	ReductionEffort int
	IccProfile      string
}
  • StripMetadata 是否去除元数据
  • Quality 图片质量,范围 0-100
  • Lossless 是否无损压缩,注意上面 Quality 100 并不代表无损压缩
  • NearLossless 是否近无损压缩
  • ReductionEffort 压缩力度,范围 0-6,用 NewWebpExportParams 的话这个值默认是 4,这里我们踩过一些坑,比如对于某些图片来说 Effort 设置为 0 会转换失败,相关的 Issue 可以见 https://github.com/libvips/libvips/issues/3568 。 (注意这里的压缩力度并不是一个线性的关系,不同的数值对应的 libvips 上是不同的压缩算法,但是数值越高,转换速度越慢)

Fun fact, 对于 AVIF 格式的导出可以使用 AvifExportParams ,内部也有 StripMetadata 选项来决定是否清除图片的源信息,但是这个功能直到 govips v2.14.0 版本发布之前都是假的,修复的 PR 是 Fix AvifExportParams StripMetadata #383