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 Ebitengine image. ebitenutil.NewImageFromFile is a utility function to create an Ebitengine 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.

NewImageFromFile calls ebiten.NewImageFromImage internally, which creates an Ebitengine image from an image.Image, and actually this is the only way to create an Ebitengine image from an image.Image. On the other hand, there are various ways to get an image.Image object.

  • 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.NewImageFromFile is the shortcut to call this OpenFile and NewImageFromImage internally.
  • 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. If you are using Go 1.16 or newer, you can use go:embed to embed a file into a Go program. Otherwiser, you can some tools 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.