github.com/pojntfx/hydrapp/hydrapp@v0.0.0-20240516002902-d08759d6ca9f/pkg/utils/convert.go (about)

     1  package utils
     2  
     3  import (
     4  	"errors"
     5  	"image"
     6  	"image/png"
     7  	"io"
     8  
     9  	ico "github.com/Kodeworks/golang-image-ico"
    10  	"golang.org/x/image/draw"
    11  	"yrh.dev/icns"
    12  )
    13  
    14  var ErrUnknownImageType = errors.New("unknown image type")
    15  
    16  type ImageType int
    17  
    18  const (
    19  	ImageTypeICO ImageType = iota
    20  	ImageTypeICNS
    21  	ImageTypePNG
    22  )
    23  
    24  func ConvertPNG(
    25  	input io.Reader,
    26  	output io.Writer,
    27  
    28  	imageType ImageType,
    29  
    30  	width int,
    31  	height int,
    32  ) error {
    33  	src, err := png.Decode(input)
    34  	if err != nil {
    35  		return err
    36  	}
    37  
    38  	dst := image.NewRGBA(image.Rect(0, 0, width, height))
    39  	draw.ApproxBiLinear.Scale(dst, dst.Bounds(), src, src.Bounds(), draw.Over, nil) // This does not report any errors
    40  
    41  	switch imageType {
    42  	case ImageTypeICO:
    43  		if err := ico.Encode(output, dst); err != nil {
    44  			return err
    45  		}
    46  
    47  	case ImageTypeICNS:
    48  		container := icns.NewICNS()
    49  
    50  		if err := container.Add(dst); err != nil {
    51  			return err
    52  		}
    53  
    54  		if err := icns.Encode(output, container); err != nil {
    55  			return err
    56  		}
    57  
    58  	case ImageTypePNG:
    59  		if err := png.Encode(output, dst); err != nil {
    60  			return err
    61  		}
    62  
    63  	default:
    64  		return ErrUnknownImageType
    65  	}
    66  
    67  	return nil
    68  }