A rendering engine library for Go supporting both SDL2 and WebAssembly (HTML Canvas) targets.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.0 KiB

  1. package render
  2. import (
  3. "errors"
  4. "image"
  5. "image/gif"
  6. "image/jpeg"
  7. "image/png"
  8. "os"
  9. "path/filepath"
  10. "golang.org/x/image/bmp"
  11. )
  12. // OpenImage opens an image file from disk.
  13. //
  14. // Supported file types are: jpeg, gif, png, bmp.
  15. func OpenImage(filename string) (image.Image, error) {
  16. fh, err := os.Open(filename)
  17. if err != nil {
  18. return nil, err
  19. }
  20. var img image.Image
  21. switch filepath.Ext(filename) {
  22. case ".jpg":
  23. fallthrough
  24. case ".jpeg":
  25. img, err = jpeg.Decode(fh)
  26. case ".png":
  27. img, err = png.Decode(fh)
  28. case ".bmp":
  29. img, err = bmp.Decode(fh)
  30. case ".gif":
  31. img, err = gif.Decode(fh)
  32. default:
  33. return nil, errors.New("unsupported file type")
  34. }
  35. return img, err
  36. }
  37. // ImageToRGBA converts a Go image.Image into an image.RGBA.
  38. func ImageToRGBA(input image.Image) *image.RGBA {
  39. var bounds = input.Bounds()
  40. var rgba = image.NewRGBA(bounds)
  41. for x := bounds.Min.X; x < bounds.Max.X; x++ {
  42. for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
  43. color := input.At(x, y)
  44. rgba.Set(x, y, color)
  45. }
  46. }
  47. return rgba
  48. }