loadimage.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2014 Hajime Hoshi
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package ebitenutil
  15. import (
  16. "image"
  17. "io"
  18. "net/http"
  19. "github.com/hajimehoshi/ebiten/v2"
  20. )
  21. // NewImageFromReader loads from the io.Reader and returns ebiten.Image and image.Image.
  22. //
  23. // Image decoders must be imported when using NewImageFromReader. For example,
  24. // if you want to load a PNG image, you'd need to add `_ "image/png"` to the import section.
  25. func NewImageFromReader(reader io.Reader) (*ebiten.Image, image.Image, error) {
  26. img, _, err := image.Decode(reader)
  27. if err != nil {
  28. return nil, nil, err
  29. }
  30. img2 := ebiten.NewImageFromImage(img)
  31. return img2, img, err
  32. }
  33. // NewImageFromURL creates a new ebiten.Image from the given URL.
  34. //
  35. // Image decoders must be imported when using NewImageFromURL. For example,
  36. // if you want to load a PNG image, you'd need to add `_ "image/png"` to the import section.
  37. func NewImageFromURL(url string) (*ebiten.Image, error) {
  38. res, err := http.Get(url)
  39. if err != nil {
  40. return nil, err
  41. }
  42. defer func() {
  43. _ = res.Body.Close()
  44. }()
  45. img, _, err := image.Decode(res.Body)
  46. if err != nil {
  47. return nil, err
  48. }
  49. eimg := ebiten.NewImageFromImage(img)
  50. return eimg, nil
  51. }