使用Go语言实现图片的读取与保存

发表时间: 2023-12-03 20:50
// import "github.com/vcaesar/imgo"// Read read the file return image.Imagefunc Read(path string) (image.Image, error) {	f, err := os.Open(path)	if err != nil {		return nil, err	}	defer f.Close()	fm := getFm(path)	return Decode(f, fm)}// Decode decode image from filefunc Decode(f *os.File, fm string) (image.Image, error) {	switch fm {	case "jpeg":		return jpeg.Decode(f)	case "png":		return png.Decode(f)	case "gif":		return gif.Decode(f)	case "bmp":		return bmp.Decode(f)	case "tiff":		return tiff.Decode(f)	default:		return nil, errors.New("Decode: Error format")	}	// return nil, nil}// Save create a image file with the image.Imagefunc Save(path string, img image.Image, quality ...int) error {	f, err := os.Create(path)	if err != nil {		return err	}	defer f.Close()	return Encode(f, img, getFm(path), quality...)}// Encode encode image to buffunc Encode(out io.Writer, subImg image.Image, fm string, quality ...int) error {	q := 70	ct := 0	if len(quality) > 0 {		q = quality[0]		ct = quality[0]	}	switch fm {	case "jpeg":		return jpeg.Encode(out, subImg, &jpeg.Options{Quality: q})	case "png":		return png.Encode(out, subImg)	case "gif":		return gif.Encode(out, subImg, &gif.Options{})	case "bmp":		return bmp.Encode(out, subImg)	case "tiff":		return tiff.Encode(out, subImg, &tiff.Options{Compression: tiff.CompressionType(ct)})	default:		return errors.New("Encode: ERROR FORMAT")	}}