Skip to content

Commit

Permalink
feat: add media package
Browse files Browse the repository at this point in the history
  • Loading branch information
thuongtruong109 committed Jul 9, 2024
1 parent 4c131f1 commit 080109e
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 6 deletions.
6 changes: 0 additions & 6 deletions media/README.md

This file was deleted.

58 changes: 58 additions & 0 deletions media/canvas.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package media

import (
"fmt"
"image"
"image/color"
"image/draw"
"log"
)

func CreateCanvas(size int) (*image.RGBA, error) {
width, height := size, size
bgColor, err := hexToRGBA("#764abc")
if err != nil {
log.Fatal(err)
}
background := image.NewRGBA(image.Rect(0, 0, width, height))
draw.Draw(background, background.Bounds(), &image.Uniform{C: bgColor},
image.Point{}, draw.Src)
return background, err
}

func hexToRGBA(hex string) (color.RGBA, error) {
var (
rgba color.RGBA
err error
errInvalidFormat = fmt.Errorf("invalid")
)
rgba.A = 0xff
if hex[0] != '#' {
return rgba, errInvalidFormat
}
hexToByte := func(b byte) byte {
switch {
case b >= '0' && b <= '9':
return b - '0'
case b >= 'a' && b <= 'f':
return b - 'a' + 10
case b >= 'A' && b <= 'F':
return b - 'A' + 10
}
err = errInvalidFormat
return 0
}
switch len(hex) {
case 7:
rgba.R = hexToByte(hex[1])<<4 + hexToByte(hex[2])
rgba.G = hexToByte(hex[3])<<4 + hexToByte(hex[4])
rgba.B = hexToByte(hex[5])<<4 + hexToByte(hex[6])
case 4:
rgba.R = hexToByte(hex[1]) * 17
rgba.G = hexToByte(hex[2]) * 17
rgba.B = hexToByte(hex[3]) * 17
default:
err = errInvalidFormat
}
return rgba, err
}
39 changes: 39 additions & 0 deletions media/image.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package media

import (
"image/jpeg"
"image/png"
"os"
"fmt"
"errors"
)

func PngToJpg(input, output string) error {
pngFile, err := os.Open(input)
if err != nil {
return formatError("Error opening PNG file", err )
}
defer pngFile.Close()

pngImage, err := png.Decode(pngFile)
if err != nil {
return formatError("Error decoding PNG file", err)
}

jpegFile, err := os.Create(output)
if err != nil {
return formatError("Error creating JPEG file", err)
}
defer jpegFile.Close()

err = jpeg.Encode(jpegFile, pngImage, nil)
if err != nil {
return formatError("Error encoding image to JPEG", err)
}

return nil
}

func formatError(message string, err error) error {
return errors.New(fmt.Sprintf("%s: %v", message, err))

Check failure on line 38 in media/image.go

View workflow job for this annotation

GitHub Actions / static-check (windows-latest, 1.19)

should use fmt.Errorf(...) instead of errors.New(fmt.Sprintf(...)) (S1028)

Check failure on line 38 in media/image.go

View workflow job for this annotation

GitHub Actions / static-check (ubuntu-latest, 1.19)

should use fmt.Errorf(...) instead of errors.New(fmt.Sprintf(...)) (S1028)
}

0 comments on commit 080109e

Please sign in to comment.