loadimage.go (2046B)
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 15 //go:build (darwin || freebsd || js || linux || windows) && !android && !ios 16 // +build darwin freebsd js linux windows 17 // +build !android 18 // +build !ios 19 20 package ebitenutil 21 22 import ( 23 "image" 24 "io" 25 26 "github.com/hajimehoshi/ebiten/v2" 27 ) 28 29 // NewImageFromFile loads the file with path and returns ebiten.Image and image.Image. 30 // 31 // Image decoders must be imported when using NewImageFromFile. For example, 32 // if you want to load a PNG image, you'd need to add `_ "image/png"` to the import section. 33 // 34 // How to solve path depends on your environment. This varies on your desktop or web browser. 35 // Note that this doesn't work on mobiles. 36 // 37 // For productions, instead of using NewImageFromFile, it is safer to embed your resources with go:embed. 38 func NewImageFromFile(path string) (*ebiten.Image, image.Image, error) { 39 file, err := OpenFile(path) 40 if err != nil { 41 return nil, nil, err 42 } 43 defer func() { 44 _ = file.Close() 45 }() 46 return NewImageFromReader(file) 47 } 48 49 // NewImageFromReader loads from the io.Reader and returns ebiten.Image and image.Image. 50 // 51 // Image decoders must be imported when using NewImageFromReader. For example, 52 // if you want to load a PNG image, you'd need to add `_ "image/png"` to the import section. 53 func NewImageFromReader(reader io.Reader) (*ebiten.Image, image.Image, error) { 54 img, _, err := image.Decode(reader) 55 if err != nil { 56 return nil, nil, err 57 } 58 img2 := ebiten.NewImageFromImage(img) 59 return img2, img, err 60 }