Golang 图片缩略

https://github.com/nfnt/resize

图片裁剪


func ImageResize() {
	file, err := os.Open("test-1.png")
	if err != nil {
		log.Fatal(err)
	}

	// decode jpeg into image.Image
	img, _, err := image.Decode(file)
	if err != nil {
		log.Fatal(err)
	}
	file.Close()

	// resize to width 1000 using Lanczos resampling
	// and preserve aspect ratio

	kuan := img.Bounds().Dx() //
	gao := img.Bounds().Dy()  //
	fmt.Println(kuan)
	fmt.Println(gao)

	m := resize.Resize(200, 0, img, resize.Lanczos3)
	//m := resize.Resize(1000, 0, img, resize.Lanczos3)

	out, err := os.Create("output-1.jpg")
	if err != nil {
		log.Fatal(err)
	}
	defer out.Close()

	// write new image to file
	jpeg.Encode(out, m, nil)
	fmt.Println("------------------")
}

[]byte 缩略

func ImageResize(ctx *gin.Context, imgByte []byte, percent uint, weight, height int) (b []byte, err error) {
	img, _, err := image.Decode(bytes.NewReader(imgByte))
	if err != nil {
		return
	}
	w := uint(weight) * percent
	h := uint(height) * percent

	resized := resize.Resize(w, h, img, resize.Lanczos3)

	buf := new(bytes.Buffer)
	if err = jpeg.Encode(buf, resized, nil); err != nil {
		return
	}
	return buf.Bytes(), nil
}