mindoc/graphics/copy.go

52 lines
1.4 KiB
Go
Raw Permalink Normal View History

2017-04-25 20:05:59 +08:00
package graphics
import (
2017-05-13 14:43:03 +08:00
"errors"
2017-04-25 20:05:59 +08:00
"image"
"os"
"github.com/nfnt/resize"
)
2017-05-13 14:43:03 +08:00
func ImageCopy(src image.Image, x, y, w, h int) (image.Image, error) {
2017-04-25 20:05:59 +08:00
var subImg image.Image
2017-05-13 14:43:03 +08:00
if rgbImg, ok := src.(*image.YCbCr); ok {
2017-04-25 20:05:59 +08:00
subImg = rgbImg.SubImage(image.Rect(x, y, x+w, y+h)).(*image.YCbCr) //图片裁剪x0 y0 x1 y1
2017-05-13 14:43:03 +08:00
} else if rgbImg, ok := src.(*image.RGBA); ok {
2017-05-10 16:47:55 +08:00
subImg = rgbImg.SubImage(image.Rect(x, y, x+w, y+h)).(*image.RGBA) //图片裁剪x0 y0 x1 y1
2017-05-13 14:43:03 +08:00
} else if rgbImg, ok := src.(*image.NRGBA); ok {
2017-05-10 16:47:55 +08:00
subImg = rgbImg.SubImage(image.Rect(x, y, x+w, y+h)).(*image.NRGBA) //图片裁剪x0 y0 x1 y1
} else if rgbImg, ok := src.(*image.Paletted); ok {
subImg = rgbImg.SubImage(image.Rect(x, y, x+w, y+h)).(*image.Paletted) //图片裁剪x0 y0 x1 y1
2017-04-25 20:05:59 +08:00
} else {
2017-05-13 14:43:03 +08:00
return subImg, errors.New("图片解码失败")
2017-04-25 20:05:59 +08:00
}
2017-05-13 14:43:03 +08:00
return subImg, nil
2017-04-25 20:05:59 +08:00
}
2017-05-13 14:43:03 +08:00
func ImageCopyFromFile(p string, x, y, w, h int) (image.Image, error) {
2017-04-25 20:05:59 +08:00
var src image.Image
file, err := os.Open(p)
if err != nil {
return src, err
}
defer file.Close()
src, _, err = image.Decode(file)
return ImageCopy(src, x, y, w, h)
}
2017-05-13 14:43:03 +08:00
func ImageResize(src image.Image, w, h int) image.Image {
2017-04-25 20:05:59 +08:00
return resize.Resize(uint(w), uint(h), src, resize.Lanczos3)
}
2017-05-13 14:43:03 +08:00
func ImageResizeSaveFile(src image.Image, width, height int, p string) error {
2017-04-25 20:05:59 +08:00
dst := resize.Resize(uint(width), uint(height), src, resize.Lanczos3)
2017-05-13 14:43:03 +08:00
return SaveImage(p, dst)
}