go语言实现图像切割

package main

import (
"errors"
"fmt"
"golang.org/x/image/bmp"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io"
"log"
"os"
"strings"

"github.com/nfnt/resize"
)

func main() {
    
    
	src := "C:\\Users\\wg\\go\\src\\学习go语言\\预处理\\家人们.png"//"png.png" 文件名
	dst := strings.Replace(src, ".", "_aa.", 1)
	fmt.Println("src=", src, " dst=", dst)
	fIn, _ := os.Open(src)
	defer fIn.Close()

	fOut, _ := os.Create(dst)
	defer fOut.Close()

	err := Clip(fIn, fOut, 0,0, 0, 0, 150, 150, 100)
	if err != nil {
    
    
		panic(err)
	}
	/*	w, h, err := Scale(fIn, fOut, 150, 150, 100)
		if err != nil {
			panic(err)
		}
		fmt.Println(w, h)*/
}


//补上缺失的代码
//* Clip 图片裁剪
//* 入参:图片输入、输出、缩略图宽、缩略图高、Rectangle{Pt(x0, y0), Pt(x1, y1)},精度
//* 规则:如果精度为0则精度保持不变
//*
//* 返回:error
// */
func Clip(in io.Reader, out io.Writer, wi, hi, x0, y0, x1, y1, quality int) (err error) {
    
    
	err = errors.New("unknow error")
	defer func() {
    
    
		if r := recover(); r != nil {
    
    
			log.Println(r)
		}
	}()
	var origin image.Image
	var fm string
	origin, fm, err = image.Decode(in)
	if err != nil {
    
    
		log.Println(err)
		return err
	}

	if wi == 0 || hi == 0 {
    
    
		wi = origin.Bounds().Max.X
		hi = origin.Bounds().Max.Y
	}
	var canvas image.Image
	if wi != origin.Bounds().Max.X {
    
    
		//先缩略
		canvas = resize.Thumbnail(uint(wi), uint(hi), origin, resize.Lanczos3)
	} else {
    
    
		canvas = origin
	}


	switch fm {
    
    
	case "jpeg":
		img := canvas.(*image.YCbCr)
		subImg := img.SubImage(image.Rect(x0, y0, x1, y1)).(*image.YCbCr)
		return jpeg.Encode(out, subImg, &jpeg.Options{
    
    quality})
	case "png":
		switch canvas.(type) {
    
    
		case *image.NRGBA:
			img := canvas.(*image.NRGBA)
			subImg := img.SubImage(image.Rect(x0, y0, x1, y1)).(*image.NRGBA)
			return png.Encode(out, subImg)
		case *image.RGBA:
			img := canvas.(*image.RGBA)
			subImg := img.SubImage(image.Rect(x0, y0, x1, y1)).(*image.RGBA)
			return png.Encode(out, subImg)
		}
	case "gif":
		img := canvas.(*image.Paletted)
		subImg := img.SubImage(image.Rect(x0, y0, x1, y1)).(*image.Paletted)
		return gif.Encode(out, subImg, &gif.Options{
    
    })
	case "bmp":
		img := canvas.(*image.RGBA)
		subImg := img.SubImage(image.Rect(x0, y0, x1, y1)).(*image.RGBA)
		return bmp.Encode(out, subImg)
	default:
		return errors.New("ERROR FORMAT")
	}
	return nil
}

猜你喜欢

转载自blog.csdn.net/zhuiyunzhugang/article/details/121246248