• Stars
    star
    383
  • Rank 107,821 (Top 3 %)
  • Language
    Lua
  • Created about 11 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Lua bindings to ImageMagick for LuaJIT using FFI

magick

test

Lua bindings to ImageMagick's MagicWand or GraphicsMagick's Wand for LuaJIT using FFI.

Installation

You'll need both LuaJIT (any version) and MagickWand or GraphicsMagickinstalled.

On Ubuntu, to use ImageMagick, you might run:

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

You can install GraphicsMagick in place of, or alongside, ImageMagick:

$ sudo apt-get install libgraphicsmagick1-dev

It's recommended to use LuaRocks to install magick.

$ sudo apt-get install luarocks
$ luarocks install magick

Basic Usage

If you just need to resize/crop an image, use the thumb function. It provides a shorthand syntax for common operations.

local magick = require("magick")
magick.thumb("input.png", "100x100", "output.png")

The second argument to thumb is a size string, it can have the following kinds of values:

"500x300"       -- Resize image such that the aspect ratio is kept,
                --  the width does not exceed 500 and the height does
                --  not exceed 300
"500x300!"      -- Resize image to 500 by 300, ignoring aspect ratio
"500x"          -- Resize width to 500 keep aspect ratio
"x300"          -- Resize height to 300 keep aspect ratio
"50%x20%"       -- Resize width to 50% and height to 20% of original
"500x300#"      -- Resize image to 500 by 300, but crop either top
                --  or bottom to keep aspect ratio
"500x300+10+20" -- Crop image to 500 by 300 at position 10,20

If you need more advanced image operations, you'll need to work with the Image object. Read on.

Functions

All functions contained in the table returned by require("magick").

thumb(input_fname, size_str, out_fname=nil)

Loads and resizes image. Write output to out_fname if provided, otherwise a string is returned with the binary data of the resulting image. (input_fname can optionally be an instance of Image)

size_str is a described above under thumb.

load_image(fname)

Return a new Image instance, loaded from filename. Returns nil and error message if image could not be loaded.

load_image_from_blob(blob)

Loads an image from a Lua string containing the binary image data.

Image object

Calling load_image or load_image_from_blob returns an Image object.

local magick = require "magick"

local img = assert(magick.load_image("hello.png"))

print("width:", img:get_width(), "height:", img:get_height());

img:resize(200, 200)
img:write("resized.png")

Images are automatically freed from memory by LuaJIT's garbage collector, but images can take up a lot of space in memory when loaded so it's recommended to call destroy on the image object as soon as possible.

Using GraphicsMagick

ImageMagick and GraphicsMagick implement (mostly) the same interface. By default the magick module will include ImageMagick. You can specify which library you use by calling require on the module for the appropriate library. At the moment it's impossible to include both libraries into the same process due to collision of function names in the C namespace.

Load ImageMagick directly:

magick = requrie "magick.wand"
local img = magick.load_image("some_image.png")

Load GraphicsMagick directly:

magick = requrie "magick.gmwand"
local img = magick.load_image("some_image.png")

Methods

Note: Not all the functionality of the respective image libraries is exposted on the Image interface. Pull requests welcome.

Methods mutate the current image when appropriate. Use clone to get an independent copy.

img:resize(w,h, f="Lanczos2", blur=1.0)

Resizes the image, f is resize function, see Filer Types

img:adaptive_resize(w,h)

Resizes the image using adaptive resize

img:crop(w,h, x=0, y=0)

Crops image to w,h where the top left is x, y

img:blur(sigma, radius=0)

Blurs the image with specified parameters. See Blur Arguments

img:rotate(degrees, r=0, g=0, b)

Rotates the image by specified number of degrees. The image dimensions will enlarge to prevent cropping. The triangles on the corners are filled with the color specified by r, g, b. The color components are specified as floating point numbers from 0 to 1.

img:sharpen(sigma, radius=0)

Sharpens the image with specified parameters. See Sharpening Images

img:resize_and_crop(w,h)

Resizes the image to w,h. The image will be cropped if necessary to maintain its aspect ratio.

img:get_blob()

Returns Lua string containing the binary data of the image. The blob is formatted the same as the image's current format (eg. PNG, Gif, etc.). Use image:set_format to change the format.

img:write(fname)

Writes the image to the specified filename

img:get_width()

Gets the width of the image

img:get_height()

Gets the height of the image

img:get_format()

Gets the current format of image as a file extension like "png" or "bmp". Use image:set_format to change the format.

img:set_format(format)

Sets the format of the image, takes a file extension like "png" or "bmp"

img:get_quality()

Gets the image compression quality.

img:set_quality(quality)

Sets the image compression quality.

img:get_gravity()

Gets the image gravity type.

img:set_gravity(gravity)

Sets the image's gravity type:

gravity can be one of the values listed in data.moon

img:get_option(magick, key)

Returns all the option names that match the specified pattern associated with a image (e.g img:get_option("webp", "lossless"))

img:set_option(magick, key, value)

Associates one or options with the img (e.g img:set_option("webp", "lossless", "0"))

img:scale(w, h)

Scale the size of an image to the given dimensions.

img:coalesce()

Coalesces the current image by compositing each frame on the previous frame. This un-optimized animated images to make them suitable for other methods.

img:composite(source, x, y, compose)

Composite another image onto another at the specified offset x, y.

compose can be one of the values listed in data.moon

img:strip()

Strips image of all profiles and comments, useful for removing exif and other data

r,g,b,a = img:get_pixel(x, y)

Get the r,g,b,a color components of a pixel in the image as doubles from 0 to 1

img:clone()

Returns a copy of the image.

img:modulate(brightness=100, saturation=100, hue=100)

Adjust the brightness, saturation, and hue of the image. See Modulate Brightness, Saturation, and Hue

img:thumb(size_str)

Mutates the image to be a thumbnail. Uses the same size string format described at the top of this README.

img:destroy()

Immediately frees the memory associated with the image, it is invalid to use the image after calling this method. It is unnecessary to call this method normally as images are tracked by the garbage collector.

Tests

Tests use Busted. Install and execute the following command to run tests. You can check the output in spec/output_images/.

$ busted

Changelog

1.6.0 - Tue Feb 2 01:18:06 PM PST 2021

  • Support ImageMagick 7
  • Fix memory leak with coalesce for ImageMagick
  • Add sharpen, set_quality, auto_orient, get_colorspace, set_colorspace, level_image, hald_clut for GraphicsMagick
  • Throw error if size string can not be parsed in thumb, handle case when source size is missing, more specs for thumb
  • Update test suite to GitHub actions, remove TravisCI
    • Test suite runs for LuaJIT beta and OpenResty's LuaJIT fork
    • Currently runs on Ubuntu: ImageMagick 6.9.10, GraphicsMagick 1.3.35, Arch Linux: ImageMagick 7.0.10.61, GraphicsMagick 1.3.36
    • Fix broken spec for modulate

1.5.0 - Tue Jun 20 13:33:41 PDT 2017

  • Add get_depth and set_depth to GraphicsMagick & ImageMagick

1.4.0 - Tue Jun 6 22:54:12 PDT 2017

  • Add reset_page to GraphicsMagick
  • Add get_format and set_format to GraphicsMagick

1.3.0 - Wed Mar 8 09:49:31 PST 2017

  • Add modulate (@granpc)
  • Add more methods to graphics magick: composite, clone, blur (@granpc)
  • Add reset page to imagemagick wand (@thierrylamarre)
  • Clone method is uses the clone function provided by image magick, garbage collects new image
  • Add thumb method on the image class

1.2.0 - Tue Jul 12 21:10:23 PDT 2016

  • Add preliminary GraphicsMagick support
  • Fix bug with gravity getter/setter (@ram-nadella)
  • Add additional wand method: #32 (@sergeyfedotov)

1.1.0 - Thu Oct 22 05:11:41 UTC 2015

  • add automatic memory management with ffi.gc
  • fix some string memory leaks when getting type and options of image
  • add coalesce, rotate methods to image
  • use pkg-config instead of MagickWand-config to query library
  • all include paths provided by config are searched instead of first

Contact

Author: Leaf Corcoran (leafo) (@moonscript)
Email: [email protected]
Homepage: http://leafo.net

More Repositories

1

moonscript

πŸŒ™ A language that compiles to Lua
Lua
3,026
star
2

lapis

A web framework for Lua and OpenResty written in MoonScript
MoonScript
2,923
star
3

sticky-kit

A jQuery plugin for creating smart sticky elements
CoffeeScript
2,919
star
4

lessphp

LESS compiler written in PHP
PHP
2,210
star
5

scssphp

SCSS compiler written in PHP
PHP
1,351
star
6

sightreading.training

🎹 Sight reading training tool
JavaScript
404
star
7

pgmoon

A pure Lua Postgres driver for use in OpenResty & more
MoonScript
376
star
8

gifine

Quickly record and edit gifs and videos of your desktop
Lua
283
star
9

etlua

Embedded Lua templates
Lua
200
star
10

aroma

a game engine: lua, opengl es 2.0, native client
C
197
star
11

streak.club

a website for running creative streaks
MoonScript
133
star
12

tableshape

Test the shape or structure of a Lua table, inspired by React.PropTypes & LPeg
MoonScript
110
star
13

gifserver

A server for transcoding gif to video on the fly
Go
102
star
14

lovekit

Miscellaneous code for making games in LOVE with MoonScript
Lua
96
star
15

moonscript-vim

MoonScript support for vim
Vim Script
96
star
16

lua-enet

Bindings to ENet for Lua
C
85
star
17

heroku-openresty

Run OpenResty on Heroku with the Lua buildpack
Lua
78
star
18

sitegen

static site generator in MoonScript
Lua
76
star
19

lua-payments

Various payment provider APIs for Lua (and OpenResty): Stripe, PayPal
MoonScript
71
star
20

web_sanitize

Lua library for sanitizing, parsing, and editing untrusted HTML
MoonScript
70
star
21

gh-actions-lua

GitHub action for Lua/LuaJIT
JavaScript
70
star
22

moonlisp

a Lisp that compiles to Lua
C
67
star
23

scssphp-compass

Compass for scssphp
PHP
66
star
24

image-server-tutorial

An example of an image processing server in OpenResty and Lua
Lua
65
star
25

compohub

A website for listing game jams
CoffeeScript
61
star
26

itchio-app-old

Desktop itch.io client
C++
45
star
27

lapis-community

Pluggable message board for Lapis powered websites
MoonScript
44
star
28

goattracker2

a fork of goattracker2
C
42
star
29

loadkit

Loadkit allows you to load arbitrary files within the Lua package path
MoonScript
41
star
30

gh-actions-luarocks

GitHub action for installing LuaRocks
JavaScript
40
star
31

lapis-console

Interactive console for working with Lapis
Lua
40
star
32

cloud_storage

A Lua library for communicating with Google Cloud Storage
Lua
40
star
33

moonscript-javascript

MoonScript compiled to JavaScript with Emscripten
JavaScript
38
star
34

moonscript-tmbundle

textmate support for MoonScript
37
star
35

lua-openai

OpenAI API bindings for Lua
MoonScript
37
star
36

lapis-bayes

Naive Bayes classifier for use in Lua
Lua
30
star
37

moonrocks

command line tool for working with rocks.moonscript.org
Lua
29
star
38

lua-twitter

A Lua twitter library that works with OpenResty or LuaSocket
Lua
27
star
39

lua-mailgun

Lua bindings to Mailgun HTTP API
MoonScript
25
star
40

ludum-dare-browser

a website for browsing ludum dare games
HTML
25
star
41

lapis-redis

Redis integration for Lapis
Lua
22
star
42

luajit-geoip

luajit bindings to maxmind geoip
MoonScript
21
star
43

lua-syntaxhighlight

A code syntax to HTML highlighter using lexers from Textadept
Lua
20
star
44

lapis-exceptions

Exception tracking for Lapis
MoonScript
16
star
45

lapis-systemd

systemd integration for lapis
Lua
16
star
46

lapis-site

The homepage for Lapis
HTML
14
star
47

lua-date

LuaDate 2 modified to work with newer versions of lua/luajit
Lua
14
star
48

mursic

sight reading training tool
MoonScript
14
star
49

moonscript-javascript-compiler

compile moonscript to javascript
MoonScript
14
star
50

moondoc

MoonScript library documentation generator
Lua
13
star
51

lapis-archlinux-docker

Dockerfile for running lapis in archlinux
Dockerfile
13
star
52

moonscript-love

LΓ–VE game engine with baked in moonscript support
C
13
star
53

lua-uinput

A Lua library for creating a virtual keyboard on Linux with uinput
MoonScript
13
star
54

lua-base58

base58 decode and encode for strings in pure lua
MoonScript
12
star
55

ludum-dare-22

A game built in 48 hours for the Ludum Dare Competition
12
star
56

moonscript-site

CSS
11
star
57

heroku-lapis-example

An example of running Lapis on Heroku with heroku-openresty
Lua
11
star
58

imagesize

Detect size & format of image file
MoonScript
10
star
59

ludum-dare-27

theme: 10 seconds
MoonScript
9
star
60

ludum-dare-25

Make a game in 48 hours!
MoonScript
9
star
61

moonscript-textadept

Textadept support for MoonScript
MoonScript
9
star
62

saltw-bot

irc/twitch bot written in MoonScript
MoonScript
9
star
63

ludum-dare-38

lets make a game "a small world"
MoonScript
8
star
64

lapis-stats

Statsd and Influxdb support for Lua, OpenResty & Lapis
Lua
8
star
65

selfwatch

inspired by selfspy
Go
8
star
66

ludum-dare-24

Let's make a video game!
7
star
67

giflib

gif
MoonScript
7
star
68

garfield

garfield comic viewer 🐱
MoonScript
7
star
69

weeklyloops

loops for http://streak.club/s/134/weekly-loop
Go
7
star
70

snes-renoise-instruments

Various snes samples ripped from spc -> xrni
7
star
71

lapis-spec-screenshot

A busted screenshot handler that takes images of your pages when testing
Lua
7
star
72

moonscrape

web scraper
MoonScript
6
star
73

lessphp-site

the lessphp homepage
PHP
6
star
74

lapis-annotate

Annotate lapis models with their schema from the database
Lua
6
star
75

dullcache

A simple large file cache for sitting in front of storage provider to offload bandwidth
Go
5
star
76

wallrun-js

Trying to get love2d game working in browser using fengari
MoonScript
5
star
77

elng

an interpreted language running on erlang
Erlang
5
star
78

ludum-dare-32

Something butt
MoonScript
4
star
79

lapis-eswidget

A widget base class designed for generating ES modules for bundling JavaScript & more
MoonScript
4
star
80

uglyphp

a templating language for php with emphasis on macros
PHP
4
star
81

fireplace

GTK+ campfire client
Python
4
star
82

album-1

my first album, chiptune
4
star
83

net.leafo.MIDIThing

Control your MIDI modules from Renoise
TeX
4
star
84

gh-actions-openresty

Install OpenResty inside of your GitHub Actions runner
JavaScript
4
star
85

ludum-dare-23

make a game in 48 hours!
4
star
86

lapis-http

HTTP library wrangler for OpenResty & Lua
MoonScript
3
star
87

somestory

lets make a game for real this time....
Lua
3
star
88

ludum-dare-30

Connected worlds
Lua
3
star
89

pixel-react

creating pixelated game interface with html in react
JavaScript
3
star
90

workdad

a chorded keyboard layout and training program
MoonScript
3
star
91

st

my terminal
Objective-C
3
star
92

awesome-config

My awesome configuration
Lua
2
star
93

godot-game-1

GDScript
2
star
94

ludum-dare-41

combine two genres
GDScript
2
star
95

noteshed

a personal wiki for notes
2
star
96

ludum-dare-31

Entire Game on One Screen
MoonScript
2
star
97

ludum-dare-40

Lets make another game
Lua
2
star
98

gslog2pg

Copy Google Cloud storage logs into PostgreSQL
MoonScript
2
star
99

moonparse

MoonScript
2
star
100

gh-actions-test

testing my action to see if it works
Lua
2
star