Skip to content
Simple wrapper to the common handling of image posting in lua
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.

POST Image handler

This library wraps the common code that is needed to handle images when they are submitted to an application over the internet.

Usage Example - Lapis

local get_image = require "image_handler".get_image
local save_image = require "image_handler".save_image

POST = function(self)
    -- Get the form posted image data from the request
    local filename =
    local content =

    -- Get the photo
    local photo = get_image(filename, content)
    -- Check result
    if not photo then
        print("Received an invalid photo")
        return { status=400 }

    -- Save the new image in the base_folder

    return { status=200 }


  • get_image(image_name, image_content) - Checks if the filename format is in the extensions whitelist, validates if the received image content has any content. Return nil in case of error, or in case of success a table with:
    name = "Random generated name so it can be stored",
    extension = "Extension of the received file",
    width = "Image Width",
    height = "Image Height",
    content = "Binary image received content",
    fullname = "Image name + extension"
  • save_image(image) - Receives the image table obtained from get_image and saves the image with the generated name in the configurated base_folder.

  • delete_image(image_name) - Receives an image fullname and deletes it from the configurated base_folder.

  • set_base_folder(path) - Changes the base folder of the images. (default "./")

  • set_allowed_formats(formats) - Sets a new table with the allowed image formats. (default {".jpg", ".png", ".jpeg", ".bmp"})


  • magick - For checking image content and gathering the image width and height.

  • printable_chars - To help in the generation of random file names.

  • Since it uses the /dev/urandom to generate file names, it can only run on a Unix based system.


Magic depends on LuaJIT and MagickWand. On Ubuntu, to use ImageMagick, you might run:

sudo apt-get install luajit
sudo apt-get install libmagickwand-dev

Use LuaRocks to install the lua packages:

sudo apt-get install luarocks
luarocks install image_handler


To run the unit tests the busted tool is needed. You can install it with luarocks:

luarocks install busted

To run the unit tests we need to tell busted to use luajit. We can test with the following command.

busted --lua /usr/bin/luajit spec
You can’t perform that action at this time.