Love2D: You can open an image from anywhere

It seems a common misconception that images cannot be loaded from outside of the source code directory, but you can. Love’s love.graphics.newImage function doesn’t accept file paths outside of the source directory, but it’s pretty easy to work around.

Assume the following file structure:

working directory/
  src/
    main.lua
  image.png

And here’s the code that will load that image:

-- images must be opened in binary mode
local file = io.open("image.png", "rb")
local data = file:read("*all")
file:close()

local byte_data = love.data.newByteData(data)
local image = love.graphics.newImage(byte_data)

I see people running into this problem all the time and no one seems to dig deeper. While it’s bad practice for many uses to do this, sometimes it’s necessary. For example, I made a little mapping program that can load maps from drag-and-drop – which always means files outside of the source directory.

Leave a Reply

Your email address will not be published. Required fields are marked *