package service import ( "fmt" "github.com/nfnt/resize" "github.com/pkg/errors" "image" "image/jpeg" "image/png" "os" "path/filepath" "time" ) func saveCroppedImage(img image.Image, imgName string, imgType string, row, col int) error { // 生成文件名(例如 part_0_0.jpg) saveDir := fmt.Sprintf("uploads/%s", time.Now().Format("2006-01-02")) os.MkdirAll(saveDir, 0755) filename := filepath.Join(saveDir, fmt.Sprintf("%s_%d_%d.%s", imgName, row, col, imgType)) outFile, err := os.Create(filename) if err != nil { return err } defer outFile.Close() // 可选:调整子图尺寸(使用 resize 库) resizedImg := resize.Resize(300, 0, img, resize.Lanczos3) // 编码为 JPEG 并保存[1](@ref) if imgType == "jpeg" { if err := jpeg.Encode(outFile, resizedImg, &jpeg.Options{Quality: 100}); err != nil { return err } } else if imgType == "png" { if err := png.Encode(outFile, resizedImg); err != nil { return err } } else { return errors.New("格式暂不支持") } return nil } func SliceImg(imagePath string, imgName string) error { // 打开图片 file, err := os.Open(imagePath) if err != nil { return errors.New("打开图片失败") } defer file.Close() // 解码图片 img, imgType, err := image.Decode(file) if err != nil { fmt.Println(err) return errors.New("解码图片失败") } // 获取原始图片尺寸 bounds := img.Bounds() width, height := bounds.Max.X, bounds.Max.Y // 计算每个小块的尺寸(假设原图可被3整除) blockWidth := width / 3 blockHeight := height / 3 // 循环切割九宫格 for row := 0; row < 3; row++ { for col := 0; col < 3; col++ { // 定义裁剪区域 rect := image.Rect( col*blockWidth, // 起始X row*blockHeight, // 起始Y (col+1)*blockWidth, // 结束X (row+1)*blockHeight, // 结束Y ) // 使用 SubImage 裁剪[3](@ref) croppedImg := img.(interface { SubImage(r image.Rectangle) image.Image }).SubImage(rect) // 保存文件(可选缩放) err = saveCroppedImage(croppedImg, imgName, imgType, row, col) if err != nil { return errors.New("保存切片图片失败") } } } return nil }