Render an image
To execute this program, you need the image file
gopher.png at the same directory:
The result will be like this:
How the code works
Imports necessary packages. The sentence
_ "image/png" means to register PNG decoder used when an image is decoded. See the standard
image package explanation for the detail.
Loads an image and creates an Ebiten image.
ebitenutil.NewImageFromFile is a utility function to create an Ebiten image object from an image file. As this seeks the specified file on the local file system, the image file must be at the specified place, or this function returns an error. As the given path is a relative path, the working directory, i.e. the place where the program is executed matters. The second argument,
ebiten.FilterDefault here, is a legacy argument. If you are not sure, use
ebiten.NewImageFromImage internally, which creates an Ebiten image from an
image.Image, and actually this is the only way to create an Ebiten image from an
image.Image. On the ohter hand, there are various ways to get an
os.Open: This is the most fundamental way to get a data for an image, but is not portable since this works only on desktops. To make matters worse, the working directory affects the result.
ebitenutil.OpenFile: This is a little better than
os.Open. This works even on browsers, but does not work on mobiles.
ebitenutil.NewImageFromFileis the shortcut to call this
ebitenutil.NewImageFromURL: This obtains an image from a specified URL. This is portable and working directory doesn't affect the result, but requires networking.
- Embedding an image file into a Go file: The most portable way is to embed the image in Go file with e.g. statik or file2byteslice. This works everywhere and is deterministic.
As an image can be reused unless disposing, the image is created once in init function.
Draws an image on an image by
(*Image).DrawImage. This function draws a given image onto the receiver image. The second argument is an option to indicate where to put the image, how colors are changed, which filter is applied, and so on. As
nil is given here, the image is rendered at the default position (upper-left corder), without changing any colors.