首页 > 其他分享 >支持不同格式之间的转换 支持图片像素的压缩以及拉长

支持不同格式之间的转换 支持图片像素的压缩以及拉长

时间:2023-01-11 23:13:25浏览次数:43  
标签:return err nil image 支持 像素 拉长 jpeg buf


  • 支持不同格式之间的转换
  • 支持图片像素的压缩以及拉长
package main

import (
	"bytes"
	"errors"
	"fmt"
	"image"
	"image/jpeg"
	"image/png"
	"io/ioutil"
	"os"

	"golang.org/x/image/draw"
	_ "golang.org/x/image/webp" // for RegisterFormat
)

type imageHelper struct {
	img      image.Image
	fileName string
	format   string
	scale    draw.Scaler
}

func NewImageHelper(fileName string, scale ...draw.Scaler) *imageHelper {
	var s draw.Scaler
	if scale == nil {
		s = draw.ApproxBiLinear
	} else {
		s = scale[0]
	}
	return &imageHelper{
		fileName: fileName,
		scale:    s,
	}
}

func (r *imageHelper) GuessFileFormat() (string, error) {
	if r.format != "" && r.img != nil {
		return r.format, nil
	}
	f, err := os.Open(r.fileName)
	if err != nil {
		return "", err
	}
	_image, s, err := image.Decode(f)
	if err != nil {
		return "", err
	}
	r.img = _image
	r.format = s

	ss := _image.Bounds()
	fmt.Println(ss)
	return s, nil
}

func (r *imageHelper) SaveAs(format string) (*bytes.Buffer, error) {
	_, err := r.GuessFileFormat()
	if err != nil {
		return nil, err
	}
	buf := bytes.Buffer{}
	switch format {
	case "jpeg", "jpg":
		err := jpeg.Encode(&buf, r.img, &jpeg.Options{Quality: 100})
		if err != nil {
			return nil, err
		}
		return &buf, nil
	case "png":
		err := png.Encode(&buf, r.img)
		if err != nil {
			return nil, err
		}
		return &buf, nil
	default:
		return nil, errors.New("invalid format")
	}
}

func (r *imageHelper) SaveAsJpeg() (*bytes.Buffer, error) {
	return r.SaveAs("jpeg")
}

func (r *imageHelper) GetSize() (int, int) {
	point := r.img.Bounds().Size()
	return point.X, point.Y
}

func (r *imageHelper) RestSize(x, y int) ([]byte, error) {
	// https://github.com/nfnt/resize/blob/master/resize_test.go
	rect := image.Rect(0, 0, x, y)
	// new img
	dst := image.NewRGBA(rect)
	buf := bytes.Buffer{}
	r.scale.Scale(dst, rect, r.img, r.img.Bounds(), draw.Over, nil)
	err := jpeg.Encode(&buf, dst, &jpeg.Options{Quality: 100})
	if err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

func main() {
	obj := NewImageHelper("webp/1.webp")
	buf, err := obj.SaveAs("png")
	if err != nil {
		return
	}
	ioutil.WriteFile("test1.png", buf.Bytes(), 0644)

	buf, err = obj.SaveAs("jpeg")
	if err != nil {
		return
	}
	ioutil.WriteFile("test2.jpeg", buf.Bytes(), 0644)

	content, _ := obj.RestSize(200, 100)
	ioutil.WriteFile("test3.jpeg", content, 0644)
}



标签:return,err,nil,image,支持,像素,拉长,jpeg,buf
From: https://www.cnblogs.com/twotigers/p/17045153.html

相关文章