Previous chapter To contents Next chapter

Chapter 12, Image

The Image module is used to manipulate bit-mapped color images. It can read PPM images and do various manipulations, or it can be used to create completely new images. The created images can be saved as PPM or converted to GIF.

All images handled by this module are stored as 24-bit RGB images. This means that a 1024 pixel wide and 1024 pixel high image will use 1024*1024*3 bytes = 3 megabytes. It is quite easy to mess up and use up all the memory by giving the wrong argument to one of the scaling functions.

Most functions in this module work by creating a new Image and then returning that instead of changing the Image you are working with. This makes it possible to share the same image between many variables without having to worry that it will be changed by accident. This can reduce the amount of memory used.

Many functions in this module work with the 'current color', this can be thought of as the background color if you wish. To change the current color you use 'setcolor'.

Let's look at an example of how this can be used:

#!/usr/local/bin/pike

int main()
{
    write("Content-type: image/gif\n\n");
    object font=Image.font();
    font->load("testfont");
    object image=font->write(ctime(time));
    write(Image.GIF.encode(image));
}
This very simple example can be used as a CGI script to produce a gif image which says what time it is in white text on a black background.

DESCRIPTION
This module adds image-drawing and -manipulating capabilities to pike.

Image.Image Basic image manipulation
Image.Font Creating images from text
Image.Colortable Color reduction, quantisation and dither
Image.Color Color names, objects and conversion
encoding/decoding image files
Image.GIF GIF encoding/decoding capabilities
Image.JPEG JPEG encoding/decoding capabilities (needs libjpeg)
Image.PNG PNG encoding/decoding capabilities (needs libz)
Image.PNM PNM (PBM/PGM/PPM) encoding/decoding capabilities
Image.XFace XFace encoding/decoding capabilities (needs libgmp)
Image.XWD XWD (X-windows dump) decoding capabilities
advanced
Image.X module for supporting X-windows low-level formats, keeping a lot of bit-mending stuff.
$Id: module.pmod,v 1.8 2000/03/22 18:12:19 peter Exp $

NOTE
Image module documentation is based on these file versions:

$Id: blit.c,v 1.37 1999/06/18 19:19:14 mirar Exp $ $Id: blit_layer_include.h,v 1.6 1999/04/13 12:32:11 mirar Exp $ $Id: colors.c,v 1.30 2000/02/03 19:02:22 grubba Exp $ $Id: colortable.c,v 1.77 1999/10/30 11:51:41 mirar Exp $ $Id: colortable.h,v 1.17 1999/04/11 12:55:43 mirar Exp $ $Id: colortable_lookup.h,v 1.9 1999/04/10 02:02:07 mirar Exp $ $Id: dct.c,v 1.14 1999/06/18 19:19:20 mirar Exp $ $Id: any.c,v 1.16 2000/03/22 18:12:19 peter Exp $ $Id: bmp.c,v 1.20 2000/02/03 12:25:18 grubba Exp $ $Id: gif.c,v 1.50 1999/11/14 22:16:08 mast Exp $ $Id: gif_lzw.c,v 1.6 1999/05/30 20:11:14 mirar Exp $ $Id: gif_lzw.h,v 1.7 1999/05/30 20:11:15 mirar Exp $ $Id: ilbm.c,v 1.13 2000/02/03 19:01:29 grubba Exp $ $Id: pnm.c,v 1.20 1999/06/19 11:08:00 mirar Exp $ $Id: x.c,v 1.26 2000/03/27 07:42:35 hubbe Exp $ $Id: xwd.c,v 1.13 2000/01/11 01:42:36 mast Exp $ $Id: font.c,v 1.58 2000/03/25 23:34:32 hubbe Exp $ $Id: image.c,v 1.160 2000/04/09 06:15:17 per Exp $ $Id: image.h,v 1.35 1999/09/25 19:58:48 grubba Exp $ $Id: layers.c,v 1.43 2000/02/22 03:41:27 per Exp $ $Id: matrix.c,v 1.22 2000/04/09 06:15:17 per Exp $ $Id: operator.c,v 1.25 1999/09/14 23:17:15 marcus Exp $ $Id: orient.c,v 1.13 1999/06/19 20:24:48 hubbe Exp $ $Id: pattern.c,v 1.18 1999/07/16 11:44:20 mirar Exp $ $Id: poly.c,v 1.3 1999/07/28 09:26:20 mirar Exp $ $Id: polyfill.c,v 1.30 1999/06/19 20:24:49 hubbe Exp $ Experimental functions.

METHOD
Image.lay

SYNTAX
Image.Layer lay(array(Image.Layer|mapping))
Image.Layer lay(array(Image.Layer|mapping), int xoffset, int yoffset, int xsize, int ysize)

DESCRIPTION
Combine layers.

RETURNS
a new layer object.

SEE ALSO
Image.Layer

METHOD
Image.load,
Image.load_layer,
Image._load

SYNTAX
object(Image.Image) load()
object(Image.Image) load(object file)
object(Image.Image) load(string filename)
object(Image.Layer) load_layer()
object(Image.Layer) load_layer(object file)
object(Image.Layer) load_layer(string filename)
mapping _load()
mapping _load(object file)
mapping _load(string filename)

DESCRIPTION
Helper function to load an image from a file. If no filename is given, Stdio.stdin is used. The result is the same as from the decode functions in Image.ANY.

NOTE
All data is read, ie nothing happens until the file is closed. Throws upon error.

12.1 Image.Image

CLASS
Image.Image

DESCRIPTION
The main object of the Image module, this object is used as drawing area, mask or result of operations.

basic:
clear, clone, create, xsize, ysize

plain drawing:
box, circle, getpixel, line, setcolor, setpixel, threshold, polyfill

operators:
`&, `*, `+, `-, `==, `>, `<, `|

pasting images:
paste, paste_alpha, paste_alpha_color, paste_mask

getting subimages, scaling, rotating:
autocrop, clone, copy, dct, mirrorx, rotate, rotate_ccw, rotate_cw, rotate_expand, scale, skewx, skewx_expand, skewy, skewy_expand

calculation by pixels:
apply_matrix, change_color, color, distancesq, grey, invert, modify_by_intensity, outline select_from, rgb_to_hsv, hsv_to_rgb,

average, max, min, sum, sumf, find_min, find_max

special pattern drawing:
noise, turbulence, test, tuned_box, gradients, random

SEE ALSO
Image, Image.Font, Image.Colortable and Image.X

METHOD
Image.Image.apply_matrix

SYNTAX
object apply_matrix(array(array(int|array(int))) matrix)
object apply_matrix(array(array(int|array(int))) matrix, int r, int g, int b)
object apply_matrix(array(array(int|array(int))) matrix, int r, int g, int b, int|float div)

DESCRIPTION
Applies a pixel-transform matrix, or filter, to the image.

2   2
pixel(x,y)= base+ k ( sum sum pixel(x+k-1,y+l-1)*matrix(k,l) )
k=0 l=0

1/k is sum of matrix, or sum of matrix multiplied with div. base is given by r,g,b and is normally black.

blur (ie a 2d gauss function):
({({1,2,1}),
({2,5,2}),
({1,2,1})})
original
sharpen (k>8, preferably 12 or 16):
({({-1,-1,-1}),
({-1, k,-1}),
({-1,-1,-1})})
edge detect:
({({1, 1,1}),
({1,-8,1}),
({1, 1,1})})
horisontal edge detect (get the idea):
({({0, 0,0}),
({1,-2,1}),
({0, 0,0})})
emboss (might prefer to begin with a grey image):
({({2, 1, 0}),
({1, 0,-1}),
({0,-1,-2})}), 128,128,128, 3
greyed

This function is not very fast.

ARGUMENTS
argument(s)description
array(array(int|array(int)))
the matrix; innermost is a value or an array with red, green, blue values for red, green, blue separation.
int r
int g
int b
base level of result, default is zero
int|float div
division factor, default is 1.0.

RETURNS
the new image object

METHOD
Image.Image.apply_max

SYNTAX
object apply_max(array(array(int|array(int))) matrix)
object apply_max(array(array(int|array(int))) matrix, int r, int g, int b)
object apply_max(array(array(int|array(int))) matrix, int r, int g, int b, int|float div)

DESCRIPTION
This is the same as apply_matrix, but it uses the maximum instead.

This function is not very fast.

ARGUMENTS
argument(s)description
array(array(int|array(int)))
the matrix; innermost is a value or an array with red, green, blue values for red, green, blue separation.
int r
int g
int b
base level of result, default is zero
int|float div
division factor, default is 1.0.

RETURNS
the new image object

NOTE
experimental status; may not be exact the same output in later versions

METHOD
Image.Image.autocrop,
Image.Image.find_autocrop

SYNTAX
object autocrop()
object autocrop(int border)
object autocrop(int border, Color color)
object autocrop(int border, int left, int right, int top, int bottom)
object autocrop(int border, int left, int right, int top, int bottom, Color color)
array(int) find_autocrop()
array(int) find_autocrop(int border)
array(int) find_autocrop(int border, int left, int right, int top, int bottom)

DESCRIPTION
Removes "unneccesary" borders around the image, adds one of its own if wanted to, in selected directions.

"Unneccesary" is all pixels that are equal -- ie if all the same pixels to the left are the same color, that column of pixels are removed.

The find_autocrop() function simply returns x1,y1,x2,y2 for the kept area. (This can be used with copy later.)

ARGUMENTS
argument(s)description
int border
int left
int right
int top
int bottom
which borders to scan and cut the image; a typical example is removing the top and bottom unneccesary pixels:
img=img->autocrop(0, 0,0,1,1);

RETURNS
the new image object

SEE ALSO
copy

METHOD
Image.Image.max,
Image.Image.min,
Image.Image.sumf,
Image.Image.sum,
Image.Image.average

SYNTAX
array(float) average()
array(int) min()
array(int) max()
array(int) sum()
array(float) sumf()

DESCRIPTION
Gives back the average, minimum, maximum color value, and the sum of all pixel's color value.

NOTE
sum() values can wrap! Most systems only have 31 bits available for positive integers. (Meaning, be careful with images that have more than 8425104 pixels.)

average() and sumf() may also wrap, but on a line basis. (Meaning, be careful with images that are wider than 8425104 pixels.) These functions may have a precision problem instead, during to limits in the 'double' C type and/or 'float' Pike type.

METHOD
Image.Image.bitscale

SYNTAX
object bitscale(float factor)
object bitscale(float xfactor, float yfactor)

DESCRIPTION
scales the image with a factor, without smoothing. This routine is faster than scale, but gives less correct results

ARGUMENTS
argument(s)description
float factor
factor to use for both x and y
float xfactor
float yfactor
separate factors for x and y

RETURNS
the new image object

METHOD
Image.Image.bitscale

SYNTAX
object bitscale(int newxsize, int newysize)
object bitscale(0, int newysize)
object bitscale(int newxsize, 0)

DESCRIPTION
scales the image to a specified new size, if one of newxsize or newysize is 0, the image aspect ratio is preserved.

ARGUMENTS
argument(s)description
int newxsize
int newysize
new image size in pixels

RETURNS
the new image object

NOTE
resulting image will be 1x1 pixels, at least

METHOD
Image.Image.box

SYNTAX
object box(int x1, int y1, int x2, int y2)
object box(int x1, int y1, int x2, int y2, int r, int g, int b)
object box(int x1, int y1, int x2, int y2, int r, int g, int b, int alpha)

DESCRIPTION
Draws a filled rectangle on the image.

original ->box(40,10,10,80,0,255,0)

ARGUMENTS
argument(s)description
int x1
int y1
int x2
int y2
box corners
int r
int g
int b
color of the box
int alpha
alpha value

RETURNS
the object called

METHOD
Image.Image.cast

SYNTAX
string cast(string type)

DESCRIPTION
Cast the image to another datatype. Currently supported are string ("rgbrgbrgb...") and array (double array of Image.Color objects).

SEE ALSO
Image.Color and Image.X

METHOD
Image.Image.change_color

SYNTAX
object change_color(int tor, int tog, int tob)
object change_color(int fromr, int fromg, int fromb,  int tor, int tog, int tob)

DESCRIPTION
Changes one color (exakt match) to another. If non-exakt-match is preferred, check distancesq and paste_alpha_color.

ARGUMENTS
argument(s)description
int tor
int tog
int tob
destination color and next current color
int fromr
int fromg
int fromb
source color, default is current color

RETURNS
a new (the destination) image object

METHOD
Image.Image.circle

SYNTAX
object circle(int x, int y, int rx, int ry)
object circle(int x, int y, int rx, int ry, int r, int g, int b)
object circle(int x, int y, int rx, int ry, int r, int g, int b, int alpha)

DESCRIPTION
Draws a circle on the image. The circle is not antialiased.

original ->circle(50,50,30,50,0,255,255)

ARGUMENTS
argument(s)description
int x
int y
circle center
int rx
int ry
circle radius in pixels
int r
int g
int b
color
int alpha
alpha value

RETURNS
the object called

METHOD
Image.Image.clear

SYNTAX
void clear()
void clear(int r, int g, int b)
void clear(int r, int g, int b, int alpha)

DESCRIPTION
gives a new, cleared image with the same size of drawing area

original ->clear(0,128,255)

ARGUMENTS
argument(s)description
int r
int g
int b
color of the new image
int alpha
new default alpha channel value

SEE ALSO
copy and clone

METHOD
Image.Image.clone

SYNTAX
object clone()
object clone(int xsize, int ysize)
object clone(int xsize, int ysize, int r, int g, int b)
object clone(int xsize, int ysize, int r, int g, int b, int alpha)

DESCRIPTION
Copies to or initialize a new image object.

original clone clone(50,50)

ARGUMENTS
argument(s)description
int xsize
int ysize
size of (new) image in pixels, called image is cropped to that size
int r
int g
int b
current color of the new image, default is black. Will also be the background color if the cloned image is empty (no drawing area made).
int alpha
new default alpha channel value

RETURNS
the new object

SEE ALSO
copy and create

METHOD
Image.Image.color

SYNTAX
object color()
object color(int value)
object color(int r, int g, int b)

DESCRIPTION
Colorize an image.

The red, green and blue values of the pixels are multiplied with the given value(s). This works best on a grey image...

The result is divided by 255, giving correct pixel values.

If no arguments are given, the current color is used as factors.

original ->color(128,128,255);

ARGUMENTS
argument(s)description
int r
int g
int b
red, green, blue factors
int value
factor

RETURNS
the new image object

SEE ALSO
grey, `* and modify_by_intensity

METHOD
Image.Image.copy

SYNTAX
object copy()
object copy(int x1, int y1, int x2, int y2)
object copy(int x1, int y1, int x2, int y2, int r, int g, int b)
object copy(int x1, int y1, int x2, int y2, int r, int g, int b, int alpha)

DESCRIPTION
Copies this part of the image. The requested area can be smaller, giving a cropped image, or bigger - the new area will be filled with the given or current color.

original ->copy(5,5,XSIZE-6,YSIZE-6) ->copy(-5,-5,XSIZE+4,YSIZE+4,10,75,10)

ARGUMENTS
argument(s)description
int x1
int y1
int x2
int y2
The requested new area. Default is the old image size.
int r
int g
int b
color of the new image
int alpha
new default alpha channel value

RETURNS
a new image object

NOTE
clone(void) and copy(void) does the same operation

SEE ALSO
clone and autocrop

METHOD
Image.Image.create

SYNTAX
void create()
void create(int xsize, int ysize)
void create(int xsize, int ysize, Color color)
void create(int xsize, int ysize, int r, int g, int b)
void create(int xsize, int ysize, int r, int g, int b, int alpha)
void create(int xsize, int ysize, string method, method ...)

DESCRIPTION
Initializes a new image object.

Image.Image(XSIZE,YSIZE) Image.Image(XSIZE,YSIZE,255,128,0)

The image can also be calculated from some special methods, for convinience:

channel modes; followed by a number of 1-char-per-pixel strings
or image objects (where red channel will be used),
or an integer value:
"grey" : make a grey image (needs 1 source: grey)
"rgb"  : make an rgb image (needs 3 sources: red, green and blue)
"cmyk" : make a rgb image from cmyk (cyan, magenta, yellow, black)

generate modes; all extra arguments is given to the generation function. These has the same name as the method: "test," "gradients" "noise" "turbulence" "random" "randomgrey" specials cases: "tuned_box" (coordinates is automatic)

ARGUMENTS
argument(s)description
int xsize
int ysize
size of (new) image in pixels
Color color
int r
int g
int b
background color (will also be current color), default color is black
int alpha
default alpha channel value

BUGS
SIGSEGVS can be caused if the size is too big, due to unchecked overflow - (xsize*ysize)&MAXINT is small enough to allocate.

SEE ALSO
copy, clone and Image.Image

METHOD
Image.Image.dct

SYNTAX
object dct(int newx, int newy)

DESCRIPTION
Scales the image to a new size.

Method for scaling is rather complex; the image is transformed via a cosine transform, and then resampled back.

This gives a quality-conserving upscale, but the algorithm used is n*n+n*m, where n and m is pixels in the original and new image.

Recommended wrapping algorithm is to scale overlapping parts of the image-to-be-scaled.

This functionality is actually added as an true experiment, but works...

ARGUMENTS
argument(s)description
int newx
int newy
new image size in pixels

RETURNS
the new image object

NOTE
Do NOT use this function if you don't know what you're dealing with! Read some signal theory first...

It write's dots on stderr, to indicate some sort of progress. It doesn't use any fct (compare: fft) algorithms.

METHOD
Image.Image.distancesq

SYNTAX
object distancesq()
object distancesq(int r, int g, int b)

DESCRIPTION
Makes an grey-scale image, for alpha-channel use.

The given value (or current color) are used for coordinates in the color cube. Each resulting pixel is the distance from this point to the source pixel color, in the color cube, squared, rightshifted 8 steps:

p = pixel color
o = given color
d = destination pixel
d.red=d.blue=d.green=
((o.red-p.red)²+(o.green-p.green)²+(o.blue-p.blue)²)>>8

original distance² to cyan ...to purple ...to yellow

ARGUMENTS
argument(s)description
int r
int g
int b
red, green, blue coordinates

RETURNS
the new image object

SEE ALSO
select_from

METHOD
Image.Image.find_min,
Image.Image.find_max

SYNTAX
array(int) find_min()
array(int) find_max()
array(int) find_min(int r, int g, int b)
array(int) find_max(int r, int g, int b)

DESCRIPTION
Gives back the position of the minimum or maximum pixel value, weighted to grey.

ARGUMENTS
argument(s)description
int r
int g
int b
weight of color, default is r=87,g=127,b=41, same as the grey() method.

METHOD
Image.Image.gamma

SYNTAX
object gamma(float g)
object gamma(float gred, ggreen, gblue)

DESCRIPTION
Calculate pixels in image by gamma curve.

Intensity of new pixels are calculated by:
i' = i^g

For example, you are viewing your image on a screen with gamma 2.2. To correct your image to the correct gamma value, do something like:

my_display_image(my_image()->gamma(1/2.2);

ARGUMENTS
argument(s)description
int g
int gred
int ggreen
int gblue
gamma value

RETURNS
a new image object

SEE ALSO
grey, `* and color

METHOD
Image.Image.getpixel

SYNTAX
array(int) getpixel(int x, int y)

DESCRIPTION

ARGUMENTS
argument(s)description
int x
int y
position of the pixel

RETURNS
color of the requested pixel -- ({int red,int green,int blue})

METHOD
Image.Image.gradients

SYNTAX
int gradients(array(int) point,  ...)
int gradients(array(int) point,  ...,  float grad)

DESCRIPTION
original 2 color
gradient
10 color
gradient
3 colors,
grad=4.0
3 colors,
grad=1.0
3 colors,
grad=0.25

RETURNS
the new image

METHOD
Image.Image.grey

SYNTAX
object grey()
object grey(int r, int g, int b)

DESCRIPTION
Makes a grey-scale image (with weighted values).

original ->grey(); ->grey(0,0,255);

ARGUMENTS
argument(s)description
int r
int g
int b
weight of color, default is r=87,g=127,b=41, which should be pretty accurate of what the eyes see...

RETURNS
the new image object

SEE ALSO
color, `* and modify_by_intensity

METHOD
Image.Image.rgb_to_hsv,
Image.Image.hsv_to_rgb

SYNTAX
object rgb_to_hsv()
object hsv_to_rgb()

DESCRIPTION
Converts RGB data to HSV data, or the other way around. When converting to HSV, the resulting data is stored like this: pixel.r = h; pixel.g = s; pixel.b = v;

When converting to RGB, the input data is asumed to be placed in the pixels as above.

original ->hsv_to_rgb(); ->rgb_to_hsv();
tuned box (below) the rainbow (below) same, but rgb_to_hsv()

HSV to RGB calculation:

in = input pixel
out = destination pixel
h=-pos*c_angle*3.1415/(float)NUM_SQUARES;
out.r=(in.b+in.g*cos(in.r));
out.g=(in.b+in.g*cos(in.r + pi*2/3));
out.b=(in.b+in.g*cos(in.r + pi*4/3));

RGB to HSV calculation: Hmm.



Example: Nice rainbow.

object i = Image.Image(200,200);
i = i->tuned_box(0,0, 200,200,
({ ({ 255,255,128 }), ({ 0,255,128 }),
({ 255,255,255 }), ({ 0,255,255 })}))
->hsv_to_rgb();

RETURNS
the new image object

METHOD
Image.Image.invert

SYNTAX
object invert()

DESCRIPTION
Invert an image. Each pixel value gets to be 255-x, where x is the old value.

original ->invert(); ->rgb_to_hsv()->invert()->hsv_to_rgb();

RETURNS
the new image object

METHOD
Image.Image.line

SYNTAX
object line(int x1, int y1, int x2, int y2)
object line(int x1, int y1, int x2, int y2, int r, int g, int b)
object line(int x1, int y1, int x2, int y2, int r, int g, int b, int alpha)

DESCRIPTION
Draws a line on the image. The line is not antialiased.

original ->line(50,10,10,50,255,0,0)

ARGUMENTS
argument(s)description
int x1
int y1
int x2
int y2
line endpoints
int r
int g
int b
color
int alpha
alpha value

RETURNS
the object called

METHOD
Image.Image.make_ascii

SYNTAX
string make_ascii(object orient1,  object orient2,  object orient3,  object orient4,  int|void xsize,  int|void ysize)

DESCRIPTION
This method creates a string that looks like the image. Example:
//Stina is an image with a cat.
array(object) Stina4=Stina->orient4();
Stina4[1]*=215;
Stina4[3]*=215;
string foo=Stina->make_ascii(@Stina4,40,4,8);

RETURNS
some nice acsii-art.

NOTE
experimental status; may not be exact the same output in later versions
      |      /    -    \
hue=  0     64   128  192  (=red in an hsv image)

SEE ALSO
orient and orient4

METHOD
Image.Image.map_closest,
Image.Image.select_colors,
Image.Image.map_fast,
Image.Image.map_fs

SYNTAX
object map_closest(array(array(int)) colors)
object map_fast(array(array(int)) colors)
object map_fs(array(array(int)) colors)
array select_colors(int num)

DESCRIPTION
Compatibility functions. Do not use!

Replacement examples:

Old code:

img=map_fs(img->select_colors(200));
New code:
img=Image.Colortable(img,200)->floyd_steinberg()->map(img);

Old code:

img=map_closest(img->select_colors(17)+({({255,255,255}),({0,0,0})}));
New code:
img=Image.Colortable(img,19,({({255,255,255}),({0,0,0})}))->map(img);

METHOD
Image.Image.match

SYNTAX
object match(int|float scale,  object needle)
object match(int|float scale,  object needle,  object haystack_cert,  object needle_cert)
object match(int|float scale,  object needle,  object haystack_avoid,  int foo)
object match(int|float scale,  object needle,  object haystack_cert,  object needle_cert,  object haystack_avoid,  int foo)

DESCRIPTION
This method creates an image that describes the match in every pixel in the image and the needle-Image.

new pixel value =
sum( my_abs(needle_pixel-haystack_pixel))

The new image only have the red rgb-part set.

ARGUMENTS
argument(s)description
int|float scale
Every pixel is divided with this value. Note that a proper value here depends on the size of the neadle.
object needle
The image to use for the matching.
object haystack_cert
This image should be the same size as the image itselves. A non-white-part of the haystack_cert-image modifies the output by lowering it.
object needle_cert
The same, but for the needle-image.
int foo
object haystack_avoid
This image should be the same size as the image itselves. If foo is less than the red value in haystack_avoid the corresponding matching-calculating is not calculated. The avoided parts are drawn in the color 0,100,0.

RETURNS
the new image object

NOTE
experimental status; may not be exact the same output in later versions

SEE ALSO
phasev and phaseh

METHOD
Image.Image.mirrorx

SYNTAX
object mirrorx()

DESCRIPTION
mirrors an image:
original ->mirrorx();

RETURNS
the new image object

METHOD
Image.Image.mirrory

SYNTAX
object mirrory()

DESCRIPTION
mirrors an image:
original ->mirrory();

METHOD
Image.Image.modify_by_intensity

SYNTAX
object modify_by_intensity(int r, int g, int b, int|array(int) v1, ..., int|array(int) vn)

DESCRIPTION
Recolor an image from intensity values.

For each color an intensity is calculated, from r, g and b factors (see grey), this gives a value between 0 and max.

The color is then calculated from the values given, v1 representing the intensity value of 0, vn representing max, and colors between representing intensity values between, linear.

original ->grey()->modify_by_intensity(1,0,0, 0,({255,0,0}),({0,255,0}));

ARGUMENTS
argument(s)description
int r
int g
int b
red, green, blue intensity factors
int|array(int) v1
int|array(int) vn
destination color

RETURNS
the new image object

SEE ALSO
grey, `* and color

METHOD
Image.Image.noise

SYNTAX
void noise(array(float|int|array(int)) colorrange)
void noise(array(float|int|array(int)) colorrange, float scale, float xdiff, float ydiff, float cscale)

DESCRIPTION
Gives a new image with the old image's size, filled width a 'noise' pattern.

The random seed may be different with each instance of pike.

Example: ->noise( ({0,({255,0,0}), 0.3,({0,255,0}), 0.6,({0,0,255}), 0.8,({255,255,0})}), 0.2,0.0,0.0,1.0 );

ARGUMENTS
argument(s)description
array(float|int|array(int)) colorrange
colorrange table
float scale
default value is 0.1
float xdiff
float ydiff
default value is 0,0
float cscale
default value is 1

SEE ALSO
turbulence

METHOD
Image.Image.orient,
Image.Image.orient4

SYNTAX
object orient(void|array(object))
array(object) orient4()

DESCRIPTION
Draws images describing the orientation of the current image.

orient gives an HSV image (run a hsv_to_rgb pass on it to get a viewable image). corresponding to the angle of the orientation:

      |      /    -    \
hue=  0     64   128  192  (=red in an hsv image)
purple cyan green red
Red, green and blue channels are added and not compared separately.

If you first use orient4 you can give its output as input to this function.

The orient4 function gives back 4 image objects, corresponding to the amount of different directions, see above.

RETURNS
an image or an array of the four new image objects

NOTE
experimental status; may not be exact the same output in later versions

METHOD
Image.Image.outline,
Image.Image.outline_mask

SYNTAX
object outline()
object outline(int olr, int olg, int olb)
object outline(int olr, int olg, int olb, int bkgr, int bkgg, int bkgb)
object outline(array(array(int)) mask)
object outline(array(array(int)) mask, int olr, int olg, int olb)
object outline(array(array(int)) mask, int olr, int olg, int olb, int bkgr, int bkgg, int bkgb)
object outline_mask()
object outline_mask(int bkgr, int bkgg, int bkgb)
object outline_mask(array(array(int)) mask)
object outline_mask(array(array(int)) mask, int bkgr, int bkgg, int bkgb)

DESCRIPTION
Makes an outline of this image, ie paints with the given color around the non-background pixels.

Default is to paint above, below, to the left and the right of these pixels.

You can also run your own outline mask.

The outline_mask function gives the calculated outline as an alpha channel image of white and black instead.

original masked
through
threshold
...and
outlined
with red

ARGUMENTS
argument(s)description
array(array(int)) mask
mask matrix. Default is ({({0,1,0}),({1,1,1}),({0,1,0})}).
int olr
int olg
int olb
outline color. Default is current.
int bkgr
int bkgg
int bkgb
background color (what color to outline to); default is color of pixel 0,0.
int|float div
division factor, default is 1.0.

RETURNS
the new image object

NOTE
no antialias!

METHOD
Image.Image.paste

SYNTAX
object paste(object image)
object paste(object image, int x, int y)

DESCRIPTION
Pastes a given image over the current image.

ARGUMENTS
argument(s)description
object image
image to paste (may be empty, needs to be an image object)
int x
int y
where to paste the image; default is 0,0

RETURNS
the object called

SEE ALSO
paste_mask, paste_alpha and paste_alpha_color

METHOD
Image.Image.paste_alpha

SYNTAX
object paste_alpha(object image, int alpha)
object paste_alpha(object image, int alpha, int x, int y)

DESCRIPTION
Pastes a given image over the current image, with the specified alpha channel value.

An alpha channel value of 0 leaves nothing of the original image in the paste area, 255 is meaningless and makes the given image invisible.

ARGUMENTS
argument(s)description
object image
image to paste
int alpha
alpha channel value
int x
int y
where to paste the image; default is 0,0

RETURNS
the object called

SEE ALSO
paste_mask, paste and paste_alpha_color

METHOD
Image.Image.paste_alpha_color

SYNTAX
object paste_alpha_color(object mask)
object paste_alpha_color(object mask, int x, int y)
object paste_alpha_color(object mask, int r, int g, int b)
object paste_alpha_color(object mask, int r, int g, int b, int x, int y)
object paste_alpha_color(object mask, Color color)
object paste_alpha_color(object mask, Color color, int x, int y)

DESCRIPTION
Pastes a given color over the current image, using the given mask as opaque channel.

A pixel value of 255 makes the result become the color given, 0 doesn't change anything.

The masks red, green and blue values are used separately. If no color are given, the current is used.

ARGUMENTS
argument(s)description
object mask
mask image
int r
int g
int b
what color to paint with; default is current
int x
int y
where to paste the image; default is 0,0

RETURNS
the object called

SEE ALSO
paste_mask, paste_alpha and paste_alpha_color

METHOD
Image.Image.paste_mask

SYNTAX
object paste_mask(object image, object mask)
object paste_mask(object image, object mask, int x, int y)

DESCRIPTION
Pastes a given image over the current image, using the given mask as opaque channel.

A pixel value of 255 makes the result become a pixel from the given image, 0 doesn't change anything.

The masks red, green and blue values are used separately.

ARGUMENTS
argument(s)description
object image
image to paste
object mask
mask image
int x
int y
where to paste the image; default is 0,0

RETURNS
the object called

SEE ALSO
paste, paste_alpha and paste_alpha_color

METHOD
Image.Image.phasev,
Image.Image.phaseh,
Image.Image.phasehv,
Image.Image.phasevh

SYNTAX
object phaseh()
object phasev()
object phasevh()
object phasehv()

DESCRIPTION
Draws images describing the phase of the current image. phaseh gives the horizontal phase and phasev the vertical phase.

phaseh gives an image where

max  falling   min  rising
value=  0     64      128   192

0 is set if there is no way to determine if it is rising or falling. This is done for the every red, green and blue part of the image.

Phase images can be used to create ugly effects or to find meta-information in the orginal image.

original phaseh() phasev() phasevh() phasehv()

RETURNS
the new image object

NOTE
experimental status; may not be exact the same output in later versions

BUGS
0 should not be set as explained above.

METHOD
Image.Image.polyfill

SYNTAX
object polyfill(array(int|float) ... curve)

DESCRIPTION
fills an area with the current color

ARGUMENTS
argument(s)description
array(int|float) curve
curve(s), ({x1,y1,x2,y2,...,xn,yn}), automatically closed.

If any given curve is inside another, it will make a hole.

RETURNS
the current object

NOTE
Lines in the polygon may not be crossed without the crossing coordinate specified in both lines.

BUGS
Inverted lines reported on Intel and Alpha processors.

SEE ALSO
setcolor

METHOD
Image.Image.random,
Image.Image.randomgrey

SYNTAX
object random()
object random(int seed)
object randomgrey()
object random(greyint seed)

DESCRIPTION
Gives a randomized image;
original ->random() ->random(17) greyed
(same again)
color(red)
(same again)
...red channel

Use with ->grey() or ->color() for one-color-results.

RETURNS
a new image

SEE ALSO
test and noise

METHOD
Image.Image.write_lsb_rgb,
Image.Image.read_lsb_grey,
Image.Image.write_lsb_grey,
Image.Image.read_lsb_rgb

SYNTAX
object write_lsb_rgb(string what)
object write_lsb_grey(string what)
string read_lsb_rgb()
string read_lsb_grey()

DESCRIPTION
These functions read/write in the least significant bit of the image pixel values. The _rgb() functions read/write on each of the red, green and blue values, and the grey keeps the same lsb on all three.

The string is nullpadded or cut to fit.

ARGUMENTS
argument(s)description
string what
the hidden message

RETURNS
the current object or the read string

METHOD
Image.Image.rotate,
Image.Image.rotate_expand

SYNTAX
object rotate(int|float angle)
object rotate(int|float angle, int r, int g, int b)
object rotate_expand(int|float angle)
object rotate_expand(int|float angle, int r, int g, int b)

DESCRIPTION
Rotates an image a certain amount of degrees (360° is a complete rotation) counter-clockwise:

original ->rotate(15,255,0,0); ->rotate_expand(15);

The "expand" variant of functions stretches the image border pixels rather then filling with the given or current color.

This rotate uses the skewx() and skewy() functions.

ARGUMENTS
argument(s)description
int|float angle
the number of degrees to rotate
int r
int g
int b
color to fill with; default is current

RETURNS
the new image object

METHOD
Image.Image.rotate_ccw

SYNTAX
object rotate_ccw()

DESCRIPTION
rotates an image counter-clockwise, 90 degrees.

original ->rotate_ccw();

RETURNS
the new image object

METHOD
Image.Image.rotate_cw

SYNTAX
object rotate_cw()

DESCRIPTION
rotates an image clockwise, 90 degrees.

original ->rotate_cw();

RETURNS
the new image object

METHOD
Image.Image.scale

SYNTAX
object scale(float factor)
object scale(0.5)
object scale(float xfactor, float yfactor)

DESCRIPTION
scales the image with a factor, 0.5 is an optimized case.

ARGUMENTS
argument(s)description
float factor
factor to use for both x and y
float xfactor
float yfactor
separate factors for x and y

RETURNS
the new image object

METHOD
Image.Image.scale

SYNTAX
object scale(int newxsize, int newysize)
object scale(0, int newysize)
object scale(int newxsize, 0)

DESCRIPTION
scales the image to a specified new size, if one of newxsize or newysize is 0, the image aspect ratio is preserved.

ARGUMENTS
argument(s)description
int newxsize
int newysize
new image size in pixels

RETURNS
the new image object

NOTE
resulting image will be 1x1 pixels, at least

METHOD
Image.Image.select_from

SYNTAX
object select_from(int x, int y)
object select_from(int x, int y, int edge_value)

DESCRIPTION
Makes an grey-scale image, for alpha-channel use.

This is very close to a floodfill.

The image is scanned from the given pixel, filled with 255 if the color is the same, or 255 minus distance in the colorcube, squared, rightshifted 8 steps (see distancesq).

When the edge distance is reached, the scan is stopped. Default edge value is 30. This value is squared and compared with the square of the distance above.

ARGUMENTS
argument(s)description
int x
int y
originating pixel in the image

RETURNS
the new image object

SEE ALSO
distancesq

METHOD
Image.Image.setcolor

SYNTAX
object setcolor(int r, int g, int b)
object setcolor(int r, int g, int b, int alpha)

DESCRIPTION
set the current color

ARGUMENTS
argument(s)description
int r
int g
int b
new color
int alpha
new alpha value

RETURNS
the object called

METHOD
Image.Image.setpixel

SYNTAX
object setpixel(int x, int y)
object setpixel(int x, int y, int r, int g, int b)
object setpixel(int x, int y, int r, int g, int b, int alpha)

DESCRIPTION
original ->setpixel(10,10,255,0,0)

ARGUMENTS
argument(s)description
int x
int y
position of the pixel
int r
int g
int b
color
int alpha
alpha value

RETURNS
the object called

METHOD
Image.Image.skewx,
Image.Image.skewx_expand

SYNTAX
object skewx(int x)
object skewx(int yfactor)
object skewx(int x, int r, int g, int b)
object skewx(int yfactor, int r, int g, int b)
object skewx_expand(int x)
object skewx_expand(int yfactor)
object skewx_expand(int x, int r, int g, int b)
object skewx_expand(int yfactor, int r, int g, int b)

DESCRIPTION
Skews an image an amount of pixels or a factor; a skew-x is a transformation:

original ->skewx(15,255,0,0); ->skewx_expand(15);

ARGUMENTS
argument(s)description
int x
the number of pixels The "expand" variant of functions stretches the image border pixels rather then filling with the given or current color.
float yfactor
best described as: x=yfactor*this->ysize()
int r
int g
int b
color to fill with; default is current

RETURNS
the new image object

METHOD
Image.Image.skewy,
Image.Image.skewy_expand

SYNTAX
object skewy(int y)
object skewy(int xfactor)
object skewy(int y, int r, int g, int b)
object skewy(int xfactor, int r, int g, int b)
object skewy_expand(int y)
object skewy_expand(int xfactor)
object skewy_expand(int y, int r, int g, int b)
object skewy_expand(int xfactor, int r, int g, int b)

DESCRIPTION
Skews an image an amount of pixels or a factor; a skew-y is a transformation:

original ->skewy(15,255,0,0); ->skewy_expand(15);

The "expand" variant of functions stretches the image border pixels rather then filling with the given or current color.

ARGUMENTS
argument(s)description
int y
the number of pixels
float xfactor
best described as: t=xfactor*this->xsize()
int r
int g
int b
color to fill with; default is current

RETURNS
the new image object

METHOD
Image.Image.test

SYNTAX
object test()
object test(int seed)

DESCRIPTION
Generates a test image, currently random gradients.

original ->test() ...and again

RETURNS
the new image

NOTE
May be subject to change or cease without prior warning.

SEE ALSO
gradients and tuned_box

METHOD
Image.Image.threshold

SYNTAX
object threshold()
object threshold(int level)
object threshold(int r, int g, int b)
object threshold(Color color)

DESCRIPTION
Makes a black-white image.

If any of red, green, blue parts of a pixel is larger then the given value, the pixel will become white, else black.

This method works fine with the grey method.

If no arguments are given, it will paint all non-black pixels white. (Ie, default is 0,0,0.)

original ->threshold(100); ->threshold(0,100,0);

RETURNS
the new image object

NOTE
The above statement "any ..." was changed from "all ..." in Pike 0.7 (9906). It also uses 0,0,0 as default input, instead of current color. This is more useful.

SEE ALSO
grey

METHOD
Image.Image.tuned_box

SYNTAX
object tuned_box(int x1, int y1, int x2, int y2, array(array(int)) corner_color)

DESCRIPTION
Draws a filled rectangle with colors (and alpha values) tuned between the corners.

Tuning function is (1.0-x/xw)*(1.0-y/yw) where x and y is the distance to the corner and xw and yw are the sides of the rectangle.

original tuned box solid tuning
(blue,red,green,yellow)
tuning transparency
(as left + 255,128,128,0)

ARGUMENTS
argument(s)description
int x1
int y1
int x2
int y2
rectangle corners
array(array(int)) corner_color
colors of the corners:
({x1y1,x2y1,x1y2,x2y2})
each of these is an array of integeres:
({r,g,b}) or ({r,g,b,alpha})
Default alpha channel value is 0 (opaque).

RETURNS
the object called

METHOD
Image.Image.turbulence

SYNTAX
void turbulence(array(float|int|array(int)) colorrange)
void turbulence(array(float|int|array(int)) colorrange, int octaves, float scale, float xdiff, float ydiff, float cscale)

DESCRIPTION
gives a new image with the old image's size, filled width a 'turbulence' pattern

The random seed may be different with each instance of pike.

Example:
->turbulence( ({0,({229,204,204}), 0.9,({229,20,20}), 0.9,Color.black}) );

ARGUMENTS
argument(s)description
array(float|int|array(int)) colorrange
colorrange table
int octaves
default value is 3
float scale
default value is 0.1
float xdiff
float ydiff
default value is 0,0
float cscale
default value is 1

SEE ALSO
noise and Image.Color

METHOD
Image.Image.xsize

SYNTAX
int xsize()

RETURNS
the width of the image

METHOD
Image.Image.ysize

SYNTAX
int ysize()

RETURNS
the height of the image

METHOD
Image.Image.`/,
Image.Image.`%

SYNTAX
object `/(object operand)
object `/(Color color)
object `/(int value)
object `%(object operand)
object `%(Color color)
object `%(int value)

DESCRIPTION
Divides pixel values and creates a new image from the result or the rest.

ARGUMENTS
argument(s)description
object operand
the other image to divide with; the images must have the same size.
Color color
int value
if specified as color or value, it will act as a whole image of that color (or value).

RETURNS
the new image object

NOTE
It isn't possible to do a modulo 256 either. (why?)

SEE ALSO
`-, `+, `|, `&, `* and Image.Layer

METHOD
Image.Image.`&

SYNTAX
object `&(object operand)
object `&(array(int) color)
object `&(int value)

DESCRIPTION
makes a new image out of the minimum pixels values

ARGUMENTS
argument(s)description
object operand
the other image to compare with; the images must have the same size.
array(int) color
an array in format ({r,g,b}), this is equal to using an uniform-colored image.
int value
equal to ({value,value,value}).

RETURNS
the new image object

SEE ALSO
`-, `+, `|, `* and Image.Layer

METHOD
Image.Image.`==,
Image.Image.`<,
Image.Image.`<

SYNTAX
int `==(object operand)
int `==(array(int) color)
int `==(int value)
int `<(object operand)
int `<(array(int) color)
int `<(int value)
int `>(object operand)
int `>(array(int) color)
int `>(int value)

DESCRIPTION
Compares an image with another image or a color.

Comparision is strict and on pixel-by-pixel basis. (Means if not all pixel r,g,b values are correct compared with the corresponding pixel values, 0 is returned.)

ARGUMENTS
argument(s)description
object operand
the other image to compare with; the images must have the same size.
array(int) color
an array in format ({r,g,b}), this is equal to using an uniform-colored image.
int value
equal to ({value,value,value}).

RETURNS
true (1) or false (0).

NOTE
`< or `> on empty ("no image") image objects or images with different size will result in an error. `== is always true on two empty image objects and always false if one and only one of the image objects is empty or the images differs in size.

a>=b and a<=b between objects is equal to !(a<b) and !(a>b), which may not be what you want (since both < and > can return false, comparing the same images).

SEE ALSO
`-, `+, `|, `* and `&

METHOD
Image.Image.`*

SYNTAX
object `*(object operand)
object `*(array(int) color)
object `*(int value)

DESCRIPTION
Multiplies pixel values and creates a new image.

This can be useful to lower the values of an image, making it greyer, for instance:

image=image*128+64;

ARGUMENTS
argument(s)description
object operand
the other image to multiply with; the images must have the same size.
array(int) color
an array in format ({r,g,b}), this is equal to using an uniform-colored image.
int value
equal to ({value,value,value}).

RETURNS
the new image object

SEE ALSO
`-, `+, `|, `& and Image.Layer

METHOD
Image.Image.`+

SYNTAX
object `+(object operand)
object `+(array(int) color)
object `+(int value)

DESCRIPTION
adds two images; values are truncated at 255.

ARGUMENTS
argument(s)description
object operand
the image which to add.
array(int) color
an array in format ({r,g,b}), this is equal to using an uniform-colored image.
int value
equal to ({value,value,value}).

RETURNS
the new image object

SEE ALSO
`-, `|, `&, `* and Image.Layer

METHOD
Image.Image.`-

SYNTAX
object `-(object operand)
object `-(array(int) color)
object `-(int value)

DESCRIPTION
makes a new image out of the difference

ARGUMENTS
argument(s)description
object operand
the other image to compare with; the images must have the same size.
array(int) color
an array in format ({r,g,b}), this is equal to using an uniform-colored image.
int value
equal to ({value,value,value}).

RETURNS
the new image object

SEE ALSO
`+, `|, `&, `*, Image.Layer, min, max and `==

METHOD
Image.Image.`|

SYNTAX
object `|(object operand)
object `|(array(int) color)
object `|(int value)

DESCRIPTION
makes a new image out of the maximum pixels values

ARGUMENTS
argument(s)description
object operand
the other image to compare with; the images must have the same size.
array(int) color
an array in format ({r,g,b}), this is equal to using an uniform-colored image.
int value
equal to ({value,value,value}).

RETURNS
the new image object

SEE ALSO
`-, `+, `&, `* and Image.Layer

12.2 Image.Colortable

CLASS
Image.Colortable

DESCRIPTION
This object keeps colortable information, mostly for image re-coloring (quantization).

The object has color reduction, quantisation, mapping and dithering capabilities.

SEE ALSO
Image, Image.Image, Image.Font and Image.GIF

METHOD
Image.Colortable.create,
Image.Colortable.add

SYNTAX
void create()
void create(array(array(int)) colors)
void create(object(Image.Image) image, int number)
void create(object(Image.Image) image, int number, array(array(int)) needed)
void create(int r, int g, int b)
void create(int r, int g, int b,  array(int) from1, array(int) to1, int steps1,  ...,  array(int) fromn, array(int) ton, int stepsn)
object add(array(array(int)) colors)
object add(object(Image.Image) image, int number)
object add(object(Image.Image) image, int number, array(array(int)) needed)
object add(int r, int g, int b)
object add(int r, int g, int b,  array(int) from1, array(int) to1, int steps1,  ...,  array(int) fromn, array(int) ton, int stepsn)

DESCRIPTION
create initiates a colortable object. Default is that no colors are in the colortable.

add takes the same argument(s) as create, thus adding colors to the colortable.

The colortable is mostly a list of colors, or more advanced, colors and weight.

The colortable could also be a colorcube, with or without additional scales. A colorcube is the by-far fastest way to find colors.

Example:

ct=colortable(my_image,256); // the best 256 colors
ct=colortable(my_image,256,({0,0,0})); // black and the best other 255

ct=colortable(({({0,0,0}),({255,255,255})})); // black and white

ct=colortable(6,7,6); // a colortable of 252 colors ct=colortable(7,7,5, ({0,0,0}),({255,255,255}),11); // a colorcube of 245 colors, and a greyscale of the rest -> 256

ARGUMENTS
argument(s)description
array(array(int)) colors
list of colors
object(Image.Image) image
source image
int number
number of colors to get from the image

0 (zero) gives all colors in the image.

Default value is 256.

array(array(int)) needed
needed colors (to optimize selection of others to these given)

this will add to the total number of colors (see argument 'number')

int r
int g
int b
size of sides in the colorcube, must (of course) be equal or larger than 2 - if smaller, the cube is ignored (no colors). This could be used to have only scales (like a greyscale) in the output.
array(int) fromi
array(int) toi
int stepi
This is to add the possibility of adding a scale of colors to the colorcube; for instance a grayscale using the arguments ({0,0,0}),({255,255,255}),17, adding a scale from black to white in 17 or more steps.

Colors already in the cube is used again to add the number of steps, if possible.

The total number of colors in the table is therefore r*b*g+step1+...+stepn.

NOTE
max hash size is (probably, set by a #define) 32768 entries, giving maybe half that number of colors as maximum.

METHOD
Image.Colortable.cast

SYNTAX
object cast(string to)

DESCRIPTION
cast the colortable to an array or mapping, the array consists of Image.Color objects and are not in index order. The mapping consists of index:Image.Color pairs, where index is the index (int) of that color.

example: (mapping)Image.Colortable(img)

ARGUMENTS
argument(s)description
string to
must be "string", "array" or "mapping".

METHOD
Image.Colortable.corners

SYNTAX
array(object) corners()

DESCRIPTION
Gives the eight corners in rgb colorspace as an array. The "black" and "white" corners are the first two.

METHOD
Image.Colortable.cubicles

SYNTAX
object cubicles()
object cubicles(int r, int g, int b)
object cubicles(int r, int g, int b, int accuracy)

DESCRIPTION
Set the colortable to use the cubicles algorithm to lookup the closest color. This is a mostly very fast and very accurate way to find the correct color, and the default algorithm.

The colorspace is divided in small cubes, each cube containing the colors in that cube. Each cube then gets a list of the colors in the cube, and the closest from the corners and midpoints between corners.

When a color is needed, the algorithm first finds the correct cube and then compares with all the colors in the list for that cube.

example: colors=Image.Colortable(img)->cubicles();

algorithm time: between O[m] and O[m * n], where n is numbers of colors and m is number of pixels

The arguments can be heavy trimmed for the usage of your colortable; a large number (10×10×10 or bigger) of cubicles is recommended when you use the colortable repeatedly, since the calculation takes much more time than usage.

recommended values:

image size  setup
100×100     cubicles(4,5,4) (default)
1000×1000   cubicles(12,12,12) (factor 2 faster than default)

In some cases, the full method is faster.

original default cubicles,
16 colors
accuracy=200

ARGUMENTS
argument(s)description
int r
int g
int b
Size, ie how much the colorspace is divided. Note that the size of each cubicle is at least about 8b, and that it takes time to calculate them. The number of cubicles are r*g*b, and default is 4,5,4, ie 80 cubicles. This works good for 200±100 colors.
int accuracy
Accuracy when checking sides of cubicles. Default is 16. A value of 1 gives complete accuracy, ie cubicle() method gives exactly the same result as full(), but takes (in worst case) 16× the time to calculate.

RETURNS
the called object

NOTE
this method doesn't figure out the cubicles, this is done on the first use of the colortable.

Not applicable to colorcube types of colortable.

METHOD
Image.Colortable.floyd_steinberg

SYNTAX
object floyd_steinberg()
object floyd_steinberg(int bidir, int|float forward, int|float downforward, int|float down, int|float downback, int|float factor)

DESCRIPTION
Set dithering method to floyd_steinberg.

The arguments to this method is for fine-tuning of the algorithm (for computer graphics wizards).

original floyd_steinberg to a 4×4×4 colorcube floyd_steinberg to 16 chosen colors

ARGUMENTS
argument(s)description
int bidir
Set algorithm direction of forward. -1 is backward, 1 is forward, 0 for toggle of direction each line (default).
int|float forward
int|float downforward
int|float down
int|float downback
Set error correction directions. Default is forward=7, downforward=1, down=5, downback=3.
int|float factor
Error keeping factor. Error will increase if more than 1.0 and decrease if less than 1.0. A value of 0.0 will cancel any dither effects. Default is 0.95.

RETURNS
the called object

METHOD
Image.Colortable.full

SYNTAX
object full()

DESCRIPTION
Set the colortable to use full scan to lookup the closest color.

example: colors=Image.Colortable(img)->full();

algorithm time: O[n*m], where n is numbers of colors and m is number of pixels

RETURNS
the called object

NOTE
Not applicable to colorcube types of colortable.

SEE ALSO
cubicles and map

METHOD
Image.Colortable.image

SYNTAX
object image()

DESCRIPTION
cast the colortable to an image object

each pixel in the image object is an entry in the colortable

RETURNS
the resulting image object

METHOD
Image.Colortable.`*,
Image.Colortable.``*,
Image.Colortable.map

SYNTAX
object map(object image)
object `*(object image)
object ``*(object image)
object map(string data, int xsize, int ysize)
object `*(string data, int xsize, int ysize)
object ``*(string data, int xsize, int ysize)

DESCRIPTION
Map colors in an image object to the colors in the colortable, and creates a new image with the closest colors.

no dither
floyd_steinberg dither
ordered dither
randomcube dither
original 2 4 8 16 32 colors

RETURNS
a new image object

NOTE
Flat (not cube) colortable and not 'full' method: this method does figure out the data needed for the lookup method, which may take time the first use of the colortable - the second use is quicker.

SEE ALSO
cubicles and full

METHOD
Image.Colortable.nodither

SYNTAX
object nodither()

DESCRIPTION
Set no dithering (default).

RETURNS
the called object

METHOD
Image.Colortable.ordered

SYNTAX
object ordered()
object ordered(int r, int g, int b)
object ordered(int r, int g, int b, int xsize, int ysize)
object ordered(int r, int g, int b, int xsize, int ysize, int x, int y)
object ordered(int r, int g, int b, int xsize, int ysize, int rx, int ry, int gx, int gy, int bx, int by)

DESCRIPTION
Set ordered dithering, which gives a position-dependent error added to the pixel values.

original mapped to
Image.Colortable(6,6,6)->
ordered
(42,42,42,2,2)
ordered() ordered
(42,42,42, 8,8,
0,0, 0,1, 1,0)

ARGUMENTS
argument(s)description
int r
int g
int b
The maximum error. Default is 32, or colorcube steps (256/size).
int xsize
int ysize
Size of error matrix. Default is 8×8. Only values which factors to multiples of 2 and 3 are possible to choose (2,3,4,6,8,12,...).
int x
int y
int rx
int ry
int gx
int gy
int bx
int by
Offset for the error matrix. x and y is for both red, green and blue values, the other is individual.

RETURNS
the called object

SEE ALSO
randomcube, nodither, floyd_steinberg and create

METHOD
Image.Colortable.randomcube,
Image.Colortable.randomgrey

SYNTAX
object randomcube()
object randomcube(int r, int g, int b)
object randomgrey()
object randomgrey(int err)

DESCRIPTION
Set random cube dithering. Color choosen is the closest one to color in picture plus (flat) random error; color±random(error).

The randomgrey method uses the same random error on red, green and blue and the randomcube method has three random errors.

original mapped to
Image.Colortable(4,4,4)->
randomcube() randomgrey()

ARGUMENTS
argument(s)description
int r
int g
int b
int err
The maximum error. Default is 32, or colorcube step.

RETURNS
the called object

NOTE
randomgrey method needs colorcube size to be the same on red, green and blue sides to work properly. It uses the red colorcube value as default.

SEE ALSO
ordered, nodither, floyd_steinberg and create

METHOD
Image.Colortable.reduce,
Image.Colortable.reduce_fs

SYNTAX
object reduce(int colors)
object reduce_fs(int colors)

DESCRIPTION
reduces the number of colors

All needed (see create) colors are kept.

reduce_fs creates and keeps the outmost corners of the color space, to improve floyd-steinberg dithering result. (It doesn't work very well, though.)

ARGUMENTS
argument(s)description
int colors
target number of colors

RETURNS
the new Colortable object

NOTE
this algorithm assumes all colors are different to begin with (!)

reduce_fs keeps the "corners" as "needed colors".

SEE ALSO
corners

METHOD
Image.Colortable.rigid

SYNTAX
object rigid()
object rigid(int r, int g, int b)

DESCRIPTION
Set the colortable to use the "rigid" method of looking up colors.

This is a very simple way of finding the correct color. The algorithm initializes a cube with r x g x b colors, where every color is chosen by closest match to the corresponding coordinate.

This format is not recommended for exact match, but may be usable when it comes to quickly view pictures on-screen.

It has a high init-cost and low use-cost. The structure is initiated at first usage.

RETURNS
the called object

NOTE
Not applicable to colorcube types of colortable.

SEE ALSO
cubicles, map and full

METHOD
Image.Colortable.spacefactors

SYNTAX
object spacefactors(int r, int g, int b)

DESCRIPTION
Colortable tuning option, this sets the color space distance factors. This is used when comparing distances in the colorspace and comparing grey levels.

Default factors are 3, 4 and 1; blue is much darker than green. Compare with Image.Image->grey().

RETURNS
the called object

NOTE
This has no sanity check. Some functions may bug if the factors are to high - color reduction functions sums grey levels in the image, this could exceed maxint in the case of high factors. Negative values may also cause strange effects. *grin*

METHOD
Image.Colortable.`+

SYNTAX
object `+(object with, ...)

DESCRIPTION
sums colortables

ARGUMENTS
argument(s)description
object(Colortable) with
Colortable object with colors to add

RETURNS
the resulting new Colortable object

METHOD
Image.Colortable.`-

SYNTAX
object `-(object with, ...)

DESCRIPTION
subtracts colortables

ARGUMENTS
argument(s)description
object(Colortable) with
Colortable object with colors to subtract

RETURNS
the resulting new Colortable object

12.3 Image.Layer

CLASS
Image.Layer

DESCRIPTION

SEE ALSO
layers

METHOD
Image.Layer.alpha,
Image.Layer.image,
Image.Layer.set_image

SYNTAX
object set_image(object(Image.Image) image)
object set_image(object(Image.Image) image, object(Image.Image) alpha_channel)
object|int(0) image()
object|int(0) alpha()

DESCRIPTION
Set/change/get image and alpha channel for the layer. You could also cancel the channels giving 0 instead of an image object.

NOTE
image and alpha channel must be of the same size, or canceled.

METHOD
Image.Layer.alpha_value,
Image.Layer.set_alpha_value

SYNTAX
object set_alpha_value(float value)
double alpha_value()

DESCRIPTION
Set/get the general alpha value of this layer. This is a float value between 0 and 1, and is multiplied with the alpha channel.

METHOD
Image.Layer.autocrop,
Image.Layer.find_autocrop

SYNTAX
object autocrop()
object autocrop(int(0..1) left, int(0..1) right, int(0..1) top, int(0..1) bottom)
array(int) find_autocrop()
array(int) find_autocrop(int(0..1) left, int(0..1) right, int(0..1) top, int(0..1) bottom)

DESCRIPTION
This crops (of finds) a suitable crop, non-destructive crop. The layer alpha channel is checked, and edges that is transparent is removed.

(What really happens is that the image and alpha channel is checked, and edges equal the fill setup is cropped away.)

find_autocrop() returns an array of xoff,yoff,xsize,ysize, which can be fed to crop().

NOTE
A tiled image will not be cropped at all.

left...bottom arguments can be used to tell what sides cropping are ok on.

SEE ALSO
crop and Image.Image->autocrop

METHOD
Image.Layer.mode,
Image.Layer.set_mode,
Image.Layer.available_modes

SYNTAX
object set_mode(string mode)
string mode()
array(string) available_modes()

DESCRIPTION
Set/get layer mode. Mode is one of these:

"normal", "add", "subtract", "multiply", "divide", "modulo", "invsubtract", "invdivide", "invmodulo", "difference", "max", "min", "bitwise_and", "bitwise_or", "bitwise_xor",

"replace", "red", "green", "blue",

"replace_hsv", "hue", "saturation", "value", "color",

"darken", "lighten",

"dissolve", "behind", "erase",

available_modes() simply gives an array containing the names of these modes.

NOTE
image and alpha channel must be of the same size, or canceled.

METHOD
Image.Layer.clone

SYNTAX
object clone()

DESCRIPTION
Creates a copy of the called object.

RETURNS
the copy

METHOD
Image.Layer.create

SYNTAX
void create(object image, object alpha, string mode)
void create(mapping info)
void create()
void create(int xsize, int ysize, object color)
void create(object color)

DESCRIPTION
The Layer construct either three arguments, the image object, alpha channel and mode, or a mapping with optional elements:
"image":image,
// default: black

"alpha":alpha, // alpha channel object // default: full opaque

"mode":string mode, // layer mode, see mode. // default: "normal"

"alpha_value":float(0.0-1.0), // layer general alpha value // default is 1.0; this is multiplied // with the alpha channel.

"xoffset":int, "yoffset":int, // offset of this layer

"fill":Color, "fill_alpha":Color, // fill color, ie what color is used // "outside" the image. default: black // and black (full transparency).

"tiled":int(0|1), // select tiling; if 1, the image // will be tiled. deafult: 0, off

The layer can also be created "empty", either giving a size and color - this will give a filled opaque square, or a color, which will set the "fill" values and fill the whole layer with an opaque color.

All values can be modified after object creation.

NOTE
image and alpha channel must be of the same size.

METHOD
Image.Layer.crop

SYNTAX
object crop(int xoff, int yoff, int xsize, int ysize)

DESCRIPTION
Crops this layer at this offset and size. Offset is not relative the layer offset, so this can be used to crop a number of layers simuntaneously.

The fill values are used if the layer is enlarged.

RETURNS
a new layer object

NOTE
The new layer object may have the same image object, if there was no cropping to be done.

METHOD
Image.Layer.fill,
Image.Layer.fill_alpha,
Image.Layer.set_fill

SYNTAX
object set_fill(Color color)
object set_fill(Color color, Color alpha)
object fill()
object fill_alpha()

DESCRIPTION
Set/query fill color and alpha, ie the color used "outside" the image. This is mostly useful if you want to "frame" a layer.

METHOD
Image.Layer.set_misc_value,
Image.Layer.get_misc_value

SYNTAX
mixed set_misc_value( mixed what,  mixed to )
mixed get_misc_value( mixed what )

DESCRIPTION
Set or query misc. attributes for the layer.

As an example, the XCF and PSD image decoders set the 'name' attribute to the name the layer had in the source file.

METHOD
Image.Layer.xoffset,
Image.Layer.yoffset,
Image.Layer.set_offset

SYNTAX
object set_offset(int x, int y)
int xoffset()
int yoffset()

DESCRIPTION
Set/query layer offset.

METHOD
Image.Layer.tiled,
Image.Layer.set_tiled

SYNTAX
object set_tiled(int yes)
int tiled()

DESCRIPTION
Set/query tiled flag. If set, the image and alpha channel will be tiled rather then framed by the fill values.

METHOD
Image.Layer.ysize,
Image.Layer.xsize

SYNTAX
int xsize()
int ysize()

DESCRIPTION
Query layer offset. This is the same as layer image/alpha image size.

12.4 Image.Font

CLASS
Image.Font

DESCRIPTION

NOTE
Short technical documentation on a font file: This object adds the text-drawing and -creation capabilities of the Image module.

For simple usage, see write and load.

other methods: baseline, height, set_xspacing_scale, set_yspacing_scale, text_extents

struct file_head
{
unsigned INT32 cookie;   - 0x464f4e54
unsigned INT32 version;  - 1
unsigned INT32 chars;    - number of chars
unsigned INT32 height;   - height of font
unsigned INT32 baseline; - font baseline
unsigned INT32 o[1];     - position of char_head's
} *fh;
struct char_head
{
unsigned INT32 width;    - width of this character
unsigned INT32 spacing;  - spacing to next character
unsigned char data[1];   - pixmap data (1byte/pixel)
} *ch;

version 2:

On-disk syntax (everything in N.B.O), int is 4 bytes, a byte is 8 bits:

pos 0 int cookie = 'FONT'; or 0x464f4e54 4 int version = 2; 1 was the old version without the last four chars 8 int numchars; Always 256 in this version of the dump program 12 int height; in (whole) pixels 16 int baseline; in (whole) pixels 20 char direction; 1==right to left, 0 is left to right 21 char format; Font format 22 char colortablep; Colortable format 23 char kerningtablep; Kerning table format

24 int offsets[numchars]; pointers into the data, realative to &cookie. [colortable] [kerningtable]

At each offset:

0 int width; in pixels 4 int spacing; in 1/1000:th of a pixels 8 char data[]; Enough data to plot width * font->height pixels Please note that if width is 0, there is no data.

Font formats: id type 0 Raw 8bit data 1 RLE encoded data, char length, char data, 70% more compact than raw data 2 ZLib compressed data 60% more compact than RLE

Colortable types: 0 No colortable (the data is an alpha channel) 1 24bit RGB with alpha (index->color, 256*4 bytes, rgba) 2 8bit Greyscale with alpha (index->color, 256*2 bytes)

Kerningtable types: 0 No kerning table 1 numchars*numchars entries, each a signed char with the kerning value 2 numchar entries, each with a list of kerning pairs, like this: int len len * (short char, short value) **!

SEE ALSO
Image and Image.Image

METHOD
Image.Font.baseline

SYNTAX
int baseline()

RETURNS
font baseline (pixels from top)

SEE ALSO
height and text_extents

METHOD
Image.Font.create

SYNTAX
void create(string filename)

DESCRIPTION
Loads a font file to this font object. Similar to load().

METHOD
Image.Font.height,
Image.Font.text_extents

SYNTAX
int height()
array(int) text_extents(string text, ...)

DESCRIPTION
Calculate extents of a text-image, that would be created by calling write with the same arguments.

ARGUMENTS
argument(s)description
string text, ...
One or more lines of text.

RETURNS
an array of width and height

SEE ALSO
write, height and baseline

METHOD
Image.Font.load

SYNTAX
object|int load(string filename)

DESCRIPTION
Loads a font file to this font object.

ARGUMENTS
argument(s)description
string filename
Font file

RETURNS
zero upon failure, font object upon success

SEE ALSO
write

METHOD
Image.Font.set_xspacing_scale,
Image.Font.set_yspacing_scale

SYNTAX
void set_xspacing_scale(float scale)
void set_yspacing_scale(float scale)

DESCRIPTION
Set spacing scale to write characters closer or more far away. This does not change scale of character, only the space between them.

ARGUMENTS
argument(s)description
float scale
what scale to use

METHOD
Image.Font.write

SYNTAX
object write(string text, ...)

DESCRIPTION
Writes some text; thus creating an image object that can be used as mask or as a complete picture.

ARGUMENTS
argument(s)description
string text, ...
One or more lines of text.

RETURNS
an Image.Image object

SEE ALSO
text_extents, load, Image.Image->paste_mask and Image.Image->paste_alpha_color

12.5 Image.colortable

CLASS
Image.colortable

12.6 Image.Poly

CLASS
Image.Poly

DESCRIPTION

12.7 Image.Color

DESCRIPTION
This module keeps names and easy handling for easy color support. It gives you an easy way to get colors from names.

A color is here an object, containing color information and methods for conversion, see below.

Image.Color can be called to make a color object. Image.Color() takes the following arguments:

Image.Color(string name)          // "red"
Image.Color(string prefix_string) // "lightblue"
Image.Color(string hex_name)      // "#ff00ff"
Image.Color(string cmyk_string)   // "%17,42,0,19.4"
Image.Color(string hsv_string)    // "%@327,90,32"
Image.Color(int red, int green, int blue)

The color names available can be listed by using indices on Image.Color. The colors are available by name directly as Image.Color.name, too:

...Image.Color.red...
...Image.Color.green...
or, maybe
import Image.Color;
...red...
...green...
...lightgreen...

Giving red, green and blue values is equal to calling Image.Color.rgb().

The prefix_string method is a form for getting modified colors, it understands all modifiers (light, dark, bright, dull and neon). Simply use "method"+"color"; (as in lightgreen, dullmagenta, lightdullorange).

The hex_name form is a simple #rrggbb form, as in HTML or X-program argument. A shorter form (#rgb) is also accepted. This is the inverse to the Image.Color.Color->hex() method.

The cmyk_string is a string form of giving cmyk (cyan, magenta, yellow, black) color. These values are floats representing percent.

The hsv_string is another hue, saturation, value representation, but in floats; hue is in degree range (0..360), and saturation and value is given in percent. This is not the same as returned or given to the hsv() methods!

NOTE
Image.Color["something"] will never(!) generate an error, but a zero_type 0, if the color is unknown. This is enough to give the error "not present in module", if used as Image.Color.something, though.

If you are using colors from for instance a webpage, you might want to create the color from Image.Color.guess(), since that method is more tolerant for mistakes and errors.

Image.Color() is case- and space-sensitive. Use Image.Color.guess() to catch all variants.

and subtract with a space (lower_case(x)-" ") to make sure you get all variants.

SEE ALSO
Image.Color.Color, Image.Color.guess, Image and Image.Colortable

METHOD
Image.Color.greylevel,
Image.Color.hsv,
Image.Color.rgb,
Image.Color.html,
Image.Color.cmyk

SYNTAX
object rgb(int red,  int green,  int blue)
object hsv(int hue,  int saturation,  int value)
object cmyk(float c, float m, float y, float k)
object greylevel(int level)
object html(string html_color)

DESCRIPTION
Creates a new color object from given red, green and blue, hue, saturation and value, or greylevel, in color value range. It could also be created from cmyk values in percent.

The html() method only understands the HTML color names, or the #rrggbb form. It is case insensitive.

RETURNS
the created object.

METHOD
Image.Color.guess

SYNTAX
object guess(string)

DESCRIPTION
This is equivalent to Image.Color(lower_case(str)-" "), and tries the color with a prepending '#' if no corresponding color is found.

RETURNS
a color object or zero_type

METHOD
Image.Color._indices,
Image.Color._values

SYNTAX
array(string) _indices()
array(object) _values()

DESCRIPTION
(ie as indices(Image.Color) or values(Image.Color)) indices gives a list of all the known color names, values gives there corresponding objects.

SEE ALSO
Image.Color

12.7.1 Image.Color.Color

CLASS
Image.Color.Color

DESCRIPTION
This is the color object. It has six readable variables, r, g, b, for the red, green and blue values, and h, s, v, for the hue, saturation anv value values.

METHOD
Image.Color.Color.neon,
Image.Color.Color.dull,
Image.Color.Color.dark,
Image.Color.Color.light,
Image.Color.Color.bright

SYNTAX
object light()
object dark()
object neon()
object bright()
object dull()

DESCRIPTION
Color modification methods. These returns a new color.

methodeffect hsvas
light raise light level±0 ±0+50
dark lower light level±0 ±0-50
brightbrighter color ±0+50+50
dull greyer color ±0-50-50
neon set to extreme ±0maxmax

light and dark lower/highers saturation when value is min-/maximised respective.

RETURNS
the new color object

NOTE
The opposites may not always take each other out. The color is maximised at white and black levels, so, for instance Image.Color.white->light()->dark() doesn't give the white color back, but the equal to Image.Color.white->dark(), since white can't get any lighter.

METHOD
Image.Color.Color.cast

SYNTAX
array|string cast()

DESCRIPTION
cast the object to an array, representing red, green and blue (equal to ->rgb()), or to a string, giving the name (equal to ->name()).

RETURNS
the name as string or rgb as array

SEE ALSO
rgb and name

METHOD
Image.Color.Color.greylevel,
Image.Color.Color.hsv,
Image.Color.Color.rgb,
Image.Color.Color.cmyk

SYNTAX
array(int) rgb()
array(int) hsv()
array(int) cmyk()
int greylevel()
int greylevel(int r,  int g,  int b)

DESCRIPTION
This is methods of getting information from an Image.Color.Color object.

They give an array of red, green and blue (rgb) values (color value),
hue, saturation and value (hsv) values (range as color value),
cyan, magenta, yellow, black (cmyk) values (in percent)
or the greylevel value (range as color value).

The greylevel is calculated by weighting red, green and blue. Default weights are 87, 127 and 41, respective, and could be given by argument.

RETURNS
array(int) respective int

SEE ALSO
Image.Color.Color and grey

METHOD
Image.Color.Color.create

SYNTAX
void create(int r, int g, int b)

DESCRIPTION
This is the main Image.Color.Color creation method, mostly for internal use.

METHOD
Image.Color.Color.grey

SYNTAX
object grey()
object grey(int red, int green, int blue)

DESCRIPTION
Gives a new color, containing a grey color, which is calculated by the greylevel method.

RETURNS
a new Image.Color.Color object

SEE ALSO
greylevel

METHOD
Image.Color.Color.name,
Image.Color.Color.hex,
Image.Color.Color.html

SYNTAX
string hex()
string hex(int n)
string name()
string html()

DESCRIPTION
Information methods.

hex() simply gives a string on the #rrggbb format. If n is given, the number of significant digits is set to this number. (Ie, n=3 gives #rrrgggbbb.)

name() is a simplified method; if the color exists in the database, the name is returned, per default is the hex() method use.

html() gives the HTML name of the color, or the hex(2) if it isn't one of the 16 HTML colors.

RETURNS
a new Image.Color.Color object

SEE ALSO
rgb, hsv and Image.Color

METHOD
Image.Color.Color.s,
Image.Color.Color.

SYNTAX
_sprintf(string s,  mapping flags)

DESCRIPTION

METHOD
Image.Color.Color.`==

SYNTAX
int `==(object other_color)
int `==(array(int) rgb)
int `==(int greylevel)
int `==(string name)

DESCRIPTION
Compares this object to another color, or color name. Example:
object red=Image.Color.red;
object other=Image.Color. ...;
object black=Image.Color.black;

if (red==other) ... if (red==({255,0,0})) ... if (black==0) ... if (red=="red") ...

RETURNS
1 or 0

NOTE
The other datatype (not color object) must be to the right!

SEE ALSO
rgb, grey and name

12.8 Image.X

DESCRIPTION
This submodule handles encoding and decoding of the binary formats of X11.

SEE ALSO
Image, Image.Image and Image.Colortable

METHOD
Image.X.decode_pseudocolor

SYNTAX
object decode_pseudocolor(string data, int width, int height, int bpp, int alignbits, int swapbytes, object colortable)

DESCRIPTION
lazy support for pseudocolor ZPixmaps

NOTE
currently, only byte-aligned pixmaps are supported

METHOD
Image.X.decode_truecolor_masks,
Image.X.decode_truecolor

SYNTAX
object decode_truecolor(string data, int width, int height, int bpp, int alignbits, int swapbytes, int rbits, int rshift, int gbits, int gshift, int bbits, int bshift)
object decode_truecolor_masks(string data, int width, int height, int bpp, int alignbits, int swapbytes, int rmask, int gmask, int bmask)

DESCRIPTION
lazy support for truecolor ZPixmaps

NOTE
currently, only byte-aligned masks are supported

METHOD
Image.X.encode_pseudocolor

SYNTAX
string encode_pseudocolor(object image, int bpp, int alignbits, int vbpp, object colortable)
string encode_pseudocolor(object image, int bpp, int alignbits, int vbpp, object colortable, string translate)

DESCRIPTION

ARGUMENTS
argument(s)description
object image
the image object to encode
int bpp
bits per pixel, how many bits each pixel should take
int vbpp
value bits per pixel; how many bits per pixel that really contains information
int alignbits
the number of even bits each line should be padded to
object colortable
colortable to get indices for pseudocolor
string translate
translate table for colors. Length of this string should be 1<<vbpp (or 2<<vbpp if vbpp are greater than 8).

NOTE
currently, only upto 16 bits pseudocolor are supported.

METHOD
Image.X.encode_truecolor,
Image.X.encode_truecolor_masks

SYNTAX
string encode_truecolor(object image, int bpp, int alignbits, int swapbytes, int rbits, int rshift, int gbits, int gshift, int bbits, int bshift)
string encode_truecolor_masks(object image, int bpp, int alignbits, int swapbytes, int rmask, int gmask, int bmask)
string encode_truecolor(object image, int bpp, int alignbits, int swapbytes, int rbits, int rshift, int gbits, int gshift, int bbits, int bshift, object ct)
string encode_truecolor_masks(object image, int bpp, int alignbits, int swapbytes, int rmask, int gmask, int bmask, object ct)

DESCRIPTION
Pack an image into a truecolor string. You will get a string of packed red, green and blue bits; ie:

encode_truecolor(img, 12,32, 0, 3,5, 4,0, 3,8) will give (aligned to even 32 bits for each row):
0bbbrrr0 gggg0bbb rrr0gggg 0bbb...
<--pixel 1--><--pixel 2--> <--3-->
10987654 32101098 76543210 1098... <- bit position <-><-> <--> | | +--- 4,0: 4 bits green shifted 0 bits | +-------- 3,5: 3 bits red shifted 5 bits +----------- 3,8: 3 bits blue shifted 8 bits

The above call is equal to
encode_truecolor_masks(img, 12,32, 0, 224, 15, 768) and
encode_truecolor(img, 12,32, 0, 3,5,4,0,3,8, colortable(1<<3,1<<4,1<<3)).
The latter gives possibility to use dither algorithms, but is slightly slower.

ARGUMENTS
argument(s)description
object image
the image object to encode
int bpp
bits per pixel, how many bits each pixel should take
int alignbits
the number of even bits each line should be padded to
int rbits
int gbits
int bbits
bits for each basecolor
int rshift
int gshift
int bshift
leftshifts for each basecolor
int rmask
int gmask
int bmask
masks for each basecolor (xbits and gbits are calculated from this), needs to be massive (no zeroes among the ones in the mask).
object ct
colortable object (for dithering, or whatever)
int swapbytes
swap bytes for bpp==16,24,32, swaps bits in the bytes if bpp==1, for change of byte/bitorder between client and server.

12.9 Image.ANY

DESCRIPTION
This method calls the other decoding methods and has some heuristics for what type of image this is.

Methods: decode, decode_alpha, _decode

SEE ALSO
Image

METHOD
Image.ANY._decode,
Image.ANY.decode,
Image.ANY.decode_alpha

SYNTAX
mapping _decode(string data)
object decode(string data)
object decode_alpha(string data)

DESCRIPTION
Tries heuristics to find the correct method of decoding the data, then calls that method.

The result of _decode() is a mapping that contains

"type":image data type (ie, "image/jpeg" or similar)
"image":the image object,
"alpha":the alpha channel or 0 if N/A

NOTE
Throws upon failure.

12.10 Image.AVS

DESCRIPTION

METHOD
Image.AVS._decode,
Image.AVS.encode,
Image.AVS.decode

SYNTAX
object decode(string data)
mapping _decode(string data)
string encode(object image)

DESCRIPTION
Handle encoding and decoding of AVS-X images. AVS is rather trivial, and not really useful, but:

An AVS file is a raw (uncompressed) 24 bit image file with alpha. The alpha channel is 8 bit, and there is no separate alpha for r, g and b.

12.11 Image.BMP

DESCRIPTION
This submodule keeps the BMP (Windows Bitmap) encode/decode capabilities of the Image module.

BMP is common in the Windows environment.

Simple encoding:
encode

SEE ALSO
Image, Image.Image and Image.Colortable

METHOD
Image.BMP._decode,
Image.BMP.decode,
Image.BMP.decode_header

SYNTAX
object decode(string data)
mapping _decode(string data)
mapping decode_header(string data)
object decode(string data, mapping options)
mapping _decode(string data, mapping options)
mapping decode_header(string data, mapping options)

DESCRIPTION
Decode a BMP.

decode gives an image object, _decode gives a mapping in the format

"type":"image/bmp",
"image":image object,
"colortable":colortable object (if applicable)

"xsize":int, "ysize":int, "compression":int, "bpp":int, "windows":int,

RETURNS
the encoded image as a string

BUGS
Doesn't support all BMP modes. At all.

SEE ALSO
encode

METHOD
Image.BMP.encode

SYNTAX
string encode(object image)
string encode(object image, mapping options)
string encode(object image, object colortable)
string encode(object image, int bpp)

DESCRIPTION
Make a BMP. It default to a 24 bpp BMP file, but if a colortable is given, it will be 8bpp with a palette entry.

option is a mapping that may contain:

"colortable": Image.Colortable   - palette
"bpp":        1|4|8|24           - force this many bits per pixel
"rle":        0|1                - run-length encode (default is 0)

ARGUMENTS
argument(s)description
object image
Source image.
object colortable
Colortable object, shortcut for "colortable" in options.

RETURNS
the encoded image as a string

BUGS
Doesn't support old BMP mode, only "windows" mode.

SEE ALSO
decode

12.12 Image.GD

DESCRIPTION
Handle encoding and decoding of GD images.

GD is the internal format of libgd by Thomas Boutell, http://www.boutell.com/gd/ It is a rather simple, uncompressed, palette format.

METHOD
Image.GD._decode,
Image.GD.decode,
Image.GD.decode_alpha,
Image.GD.decode_header

SYNTAX
object decode(string data)
object decode_alpha(string data)
mapping decode_header(string data)
mapping _decode(string data)

DESCRIPTION
decodes a GD image

The decode_header and _decode has these elements:

"image":object            - image object    \
"alpha":object            - decoded alpha   |- not decode_header
"colortable":object       - decoded palette /

"type":"image/x-gd" - image type "xsize":int - horisontal size in pixels "ysize":int - vertical size in pixels "alpha_index":int - index to transparancy in palette -1 means no transparency "colors":int - numbers of colors

METHOD
Image.GD.encode

SYNTAX
string encode(object image)
string encode(object image, mapping options)

DESCRIPTION
encode a GD image

options is a mapping with optional values:

"colortable":object       - palette to use (max 256 colors)
"alpha":object            - alpha channel (truncated to 1 bit)
"alpha_index":int         - index to transparancy in palette

12.13 Image.GIF

DESCRIPTION
This submodule keep the GIF encode/decode capabilities of the Image module.

GIF is a common image storage format, usable for a limited color palette - a GIF image can only contain as most 256 colors - and animations.

Simple encoding: encode, encode_trans

Advanced stuff: render_block, header_block, end_block, netscape_loop_block

Very advanced stuff: _render_block, _gce_block

SEE ALSO
Image, Image.Image and Image.Colortable

METHOD
Image.GIF.decode

SYNTAX
object decode(string data)
object decode(array _decoded)
object decode(array __decoded)

DESCRIPTION
Decodes GIF data and creates an image object.

RETURNS
the decoded image as an image object

NOTE
This function may throw errors upon illegal GIF data. This function uses __decode, _decode, Image.Image->paste and Image.Image->paste_alpha internally.

SEE ALSO
encode

METHOD
Image.GIF.decode_layers,
Image.GIF.decode_layer

SYNTAX
object decode_layers(string data)
object decode_layers(array _decoded)
object decode_layer(string data)
object decode_layer(array _decoded)

DESCRIPTION
Decodes GIF data and creates an array of layers or the resulting layer.

NOTE
The resulting layer may not have the same size as the gif image, but the resulting bounding box of all render chunks in the gif file. The offset should be correct, though.

SEE ALSO
encode and decode_map

METHOD
Image.GIF.decode_map

SYNTAX
mapping decode_map(INT32 args)

DESCRIPTION
Returns a mapping similar to other decoders _decode function.

"image":the image
"alpha":the alpha channel

"xsize":int "ysize":int size of image "type":"image/gif" file type information as MIME type

NOTE
The wierd name of this function (not _decode as the other decoders) is because gif was the first decoder and was written before the API was finally defined. Sorry about that. /Mirar

METHOD
Image.GIF.encode,
Image.GIF.encode_trans

SYNTAX
string encode(object img);
string encode(object img, int colors);
string encode(object img, object colortable);
string encode_trans(object img, object alpha);
string encode_trans(object img, int tr_r, int tr_g, int tr_b);
string encode_trans(object img, int colors, object alpha);
string encode_trans(object img, int colors, int tr_r, int tr_g, int tr_b);
string encode_trans(object img, int colors, object alpha, int tr_r, int tr_g, int tr_b);
string encode_trans(object img, object colortable, object alpha);
string encode_trans(object img, object colortable, int tr_r, int tr_g, int tr_b);
string encode_trans(object img, object colortable, object alpha, int a_r, int a_g, int a_b);
string encode_trans(object img, object colortable, int transp_index);

DESCRIPTION
Create a complete GIF file.

The latter (encode_trans) functions add transparency capabilities.

Example:

img=Image.Image([...]);
[...] // make your very-nice image
write(Image.GIF.encode(img)); // write it as GIF on stdout

ARGUMENTS
argument(s)description
object img
The image which to encode.
int colors
object colortable
These arguments decides what colors the image should be encoded with. If a number is given, a colortable with be created with (at most) that amount of colors. Default is '256' (GIF maximum amount of colors).
object alpha
Alpha channel image (defining what is transparent); black color indicates transparency. GIF has only transparent or nontransparent (no real alpha channel). You can always dither a transparency channel: Image.Colortable(my_alpha, ({({0,0,0}),({255,255,255})})) ->full()->floyd_steinberg()->map(my_alpha)
int tr_r
int tr_g
int tr_b
Use this (or the color closest to this) color as transparent pixels.
int a_r
int a_g
int a_b
Encode transparent pixels (given by alpha channel image) to have this color. This option is for making GIFs for the decoders that doesn't support transparency.
int transp_index
Use this color no in the colortable as transparent color.

NOTE
For advanced users:
Image.GIF.encode_trans(img,colortable,alpha);
is equivalent of using
Image.GIF.header_block(img->xsize(),img->ysize(),colortable)+
Image.GIF.render_block(img,colortable,0,0,0,alpha)+
Image.GIF.end_block();
and is actually implemented that way.

METHOD
Image.GIF.end_block

SYNTAX
string end_block();

DESCRIPTION
This function gives back a GIF end (trailer) block.

RETURNS
the end block as a string.

NOTE
This is in the advanced sector of the GIF support; please read some about how GIFs are packed.

The result of this function is always ";" or "\x3b", but I recommend using this function anyway for code clearity.

SEE ALSO
header_block and end_block

METHOD
Image.GIF.header_block

SYNTAX
string header_block(int xsize, int ysize, int numcolors);
string header_block(int xsize, int ysize, object colortable);
string header_block(int xsize, int ysize, object colortable, int background_color_index, int gif87a, int aspectx, int aspecty);
string header_block(int xsize, int ysize, object colortable, int background_color_index, int gif87a, int aspectx, int aspecty, int r, int g, int b);

DESCRIPTION
This function gives back a GIF header block.

Giving a colortable to this function includes a global palette in the header block.

ARGUMENTS
argument(s)description
int xsize
int ysize
Size of drawing area. Usually same size as in the first (or only) render block(s).
int background_color_index
This color in the palette is the background color. Background is visible if the following render block(s) doesn't fill the drawing area or are transparent. Most decoders doesn't use this value, though.
int gif87a
If set, write 'GIF87a' instead of 'GIF89a' (default 0 == 89a).
int aspectx
int aspecty
Aspect ratio of pixels, ranging from 4:1 to 1:4 in increments of 1/16th. Ignored by most decoders. If any of aspectx or aspecty is zero, aspectratio information is skipped.
int r
int g
int b
Add this color as the transparent color. This is the color used as transparency color in case of alpha-channel given as image object. This increases (!) the number of colors by one.

RETURNS
the created header block as a string

NOTE
This is in the advanced sector of the GIF support; please read some about how GIFs are packed.

This GIF encoder doesn't support different size of colors in global palette and color resolution.

SEE ALSO
header_block and end_block

METHOD
Image.GIF.netscape_loop_block

SYNTAX
string netscape_loop_block();
string netscape_loop_block(int number_of_loops);

DESCRIPTION
Creates a application-specific extention block; this block makes netscape and compatible browsers loop the animation a certain amount of times.

ARGUMENTS
argument(s)description
int number_of_loops
Number of loops. Max and default is 65535.

METHOD
Image.GIF.render_block

SYNTAX
string render_block(object img, object colortable, int x, int y, int localpalette);
string render_block(object img, object colortable, int x, int y, int localpalette, object alpha);
string render_block(object img, object colortable, int x, int y, int localpalette, object alpha, int r, int g, int b);
string render_block(object img, object colortable, int x, int y, int localpalette, int delay, int transp_index, int interlace, int user_input, int disposal);
string render_block(object img, object colortable, int x, int y, int localpalette, object alpha, int r, int g, int b, int delay, int interlace, int user_input, int disposal);

DESCRIPTION
This function gives a image block for placement in a GIF file, with or without transparency. The some options actually gives two blocks, the first with graphic control extensions for such things as delay or transparency.

Example:

img1=Image.Image([...]);
img2=Image.Image([...]);
[...] // make your very-nice images
nct=Image.Colortable([...]); // make a nice colortable
write(Image.GIF.header_block(xsize,ysize,nct)); // write a GIF header
write(Image.GIF.render_block(img1,nct,0,0,0,10)); // write a render block
write(Image.GIF.render_block(img2,nct,0,0,0,10)); // write a render block
[...]
write(Image.GIF.end_block()); // write end block
// voila! A GIF animation on stdout.

The above animation is thus created:

object nct=colortable(lena,32,({({0,0,0})}));
string s=GIF.header_block(lena->xsize(),lena->ysize(),nct);
foreach ( ({lena->xsize(),
(int)(lena->xsize()*0.75),
(int)(lena->xsize()*0.5),
(int)(lena->xsize()*0.25),
(int)(1),
(int)(lena->xsize()*0.25),
(int)(lena->xsize()*0.5),
(int)(lena->xsize()*0.75)}),int xsize)
{
object o=lena->scale(xsize,lena->ysize());
object p=lena->clear(0,0,0);
p->paste(o,(lena->xsize()-o->xsize())/2,0);
s+=GIF.render_block(p,nct,0,0,0,25);
}
s+=GIF.netscape_loop_block(200);
s+=GIF.end_block();
write(s);

ARGUMENTS
argument(s)description
object img
The image.
object colortable
Colortable with colors to use and to write as palette.
int x
int y
Position of this image.
int localpalette
If set, writes a local palette.
object alpha
Alpha channel image; black is transparent.
int r
int g
int b
Color of transparent pixels. Not all decoders understands transparency. This is ignored if localpalette isn't set.
int delay
View this image for this many centiseconds. Default is zero.
int transp_index
Index of the transparent color in the colortable. -1 indicates no transparency.
int user_input
If set: wait the delay or until user input. If delay is zero, wait indefinitely for user input. May sound the bell upon decoding. Default is non-set.
int disposal
Disposal method number;
0
No disposal specified. The decoder is not required to take any action. (default)
1
Do not dispose. The graphic is to be left in place.
2
Restore to background color. The area used by the graphic must be restored to the background color.
3
Restore to previous. The decoder is required to restore the area overwritten by the graphic with what was there prior to rendering the graphic.
4-7
To be defined.

NOTE
This is in the advanced sector of the GIF support; please read some about how GIFs are packed.

The user_input and disposal method are unsupported in most decoders.

SEE ALSO
encode, header_block and end_block

METHOD
Image.GIF._decode

SYNTAX
array _decode(string gifdata);
array _decode(array __decoded);

DESCRIPTION
Decodes a GIF image structure down to chunks, and also decode the images in the render chunks.

({int xsize,int ysize,    // 0: size of image drawing area
void|object colortable, // 2: opt. global colortable
({ int aspx, int aspy,  // 3 0: aspect ratio or 0, 0 if not set
int background }),   //   2: index of background color
followed by any number these blocks in any order (gce chunks are decoded and incorporated in the render chunks):
({ GIF.RENDER,          //   0: block identifier
int x, int y,         //   1: position of render
object image,         //   3: render image
void|object alpha,    //   4: 0 or render alpha channel
object colortable,    //   5: colortable (may be same as global)

int interlace, // 6: interlace flag int trans_index, // 7: 0 or transparent color index int delay, // 8: 0 or delay in centiseconds int user_input, // 9: user input flag int disposal}) // 10: disposal method number (0..7)

({ GIF.EXTENSION, // 0: block identifier int extension, // 1: extension number string data }) // 2: extension data

and possibly ended with one of these:
({ GIF.ERROR_PREMATURE_EOD })   // premature end-of-data

({ GIF.ERROR_TOO_MUCH_DATA, // data following end marker string data }) // (rest of file)

({ GIF.ERROR_UNKNOWN_DATA, // unknown data string data }) // (rest of file)

The decode method uses this data in a way similar to this program:

import Image;

object my_decode_gif(string data) { array a=GIF._decode(data); object img=image(a[0],a[1]); foreach (a[4..],array b) if (b[0]==GIF.RENDER) if (b[4]) img->paste_alpha(b[3],b[4],b[1],b[2]); else img->paste(b[3],b[1],b[2]); return img; }

ARGUMENTS
argument(s)description
string gifdata
GIF data (with header and all)
array __decoded
GIF data as from __decode

RETURNS
the above array

NOTE
May throw errors if the GIF header is incomplete or illegal.

This is in the very advanced sector of the GIF support; please read about how GIF files works.

METHOD
Image.GIF._encode

SYNTAX
string _encode(array data)

DESCRIPTION
Encodes GIF data; reverses _decode.

ARGUMENTS
argument(s)description
array data
data as returned from _encode

NOTE
Some given values in the array are ignored. This function does not give the _exact_ data back!

METHOD
Image.GIF._gce_block

SYNTAX
string _gce_block(int transparency, int transparency_index, int delay, int user_input, int disposal);

DESCRIPTION
This function gives back a Graphic Control Extension block. A GCE block has the scope of the following render block.

ARGUMENTS
argument(s)description
int transparency
int transparency_index
The following image has transparency, marked with this index.
int delay
View the following rendering for this many centiseconds (0..65535).
int user_input
Wait the delay or until user input. If delay is zero, wait indefinitely for user input. May sound the bell upon decoding.
int disposal
Disposal method number;
0
No disposal specified. The decoder is not required to take any action.
1
Do not dispose. The graphic is to be left in place.
2
Restore to background color. The area used by the graphic must be restored to the background color.
3
Restore to previous. The decoder is required to restore the area overwritten by the graphic with what was there prior to rendering the graphic.
4-7
To be defined.

NOTE
This is in the very advanced sector of the GIF support; please read about how GIF files works.

Most decoders just ignore some or all of these parameters.

SEE ALSO
_render_block and render_block

METHOD
Image.GIF._render_block

SYNTAX
string _render_block(int x, int y, int xsize, int ysize, int bpp, string indices, 0|string colortable, int interlace);

DESCRIPTION
Advanced (!) method for writing renderblocks for placement in a GIF file. This method only applies LZW encoding on the indices and makes the correct headers.

ARGUMENTS
argument(s)description
int x
int y
Position of this image.
int xsize
int ysize
Size of the image. Length if the indices string must be xsize*ysize.
int bpp
Bits per pixels in the indices. Valid range 1..8.
string indices
The image indices as an 8bit indices.
string colortable
Colortable with colors to write as palette. If this argument is zero, no local colortable is written. Colortable string len must be 1<<bpp.
int interlace
Interlace index data and set interlace bit. The given string should _not_ be pre-interlaced.

NOTE
This is in the very advanced sector of the GIF support; please read about how GIF files works.

SEE ALSO
encode, _encode, header_block and end_block

METHOD
Image.GIF.__decode

SYNTAX
array __decode();

DESCRIPTION
Decodes a GIF image structure down to chunks and

({int xsize,int ysize,      // 0: size of image drawing area
int numcol,               // 2: suggested number of colors
void|string colortable,   // 3: opt. global colortable
({ int aspx, int aspy,    // 4,0: aspect ratio or 0, 0 if not set
int background }),     //   1: index of background color
followed by any number these blocks in any order:
({ GIF.EXTENSION,         //   0: block identifier
int extension,         //   1: extension number
string data })         //   2: extension data

({ GIF.RENDER, // 0: block identifier int x, int y, // 1: position of render int xsize, int ysize, // 3: size of render int interlace, // 5: interlace flag void|string colortbl, // 6: opt. local colortable int lzwsize, // 7: lzw code size string lzwdata }) // 8: packed lzw data

and possibly ended with one of these:
({ GIF.ERROR_PREMATURE_EOD })   // premature end-of-data

({ GIF.ERROR_TOO_MUCH_DATA, // data following end marker string data }) // (rest of file)

({ GIF.ERROR_UNKNOWN_DATA, // unknown data string data }) // (rest of file)

RETURNS
the above array

NOTE
May throw errors if the GIF header is incomplete or illegal.

This is in the very advanced sector of the GIF support; please read about how GIF files works.

12.14 Image.HRZ

DESCRIPTION

METHOD
Image.HRZ._decode,
Image.HRZ.encode,
Image.HRZ.decode

SYNTAX
object decode(string data)
mapping _decode(string data)
string encode(object image)

DESCRIPTION
Handle encoding and decoding of HRZ images. HRZ is rather trivial, and not really useful, but:

The HRZ file is always 256x240 with RGB values from 0 to 63. No compression, no header, just the raw RGB data. HRZ is (was?) used for amatuer radio slow-scan TV.

12.15 Image.ILBM

DESCRIPTION
This submodule keep the ILBM encode/decode capabilities of the Image module.

SEE ALSO
Image, Image.Image and Image.Colortable

METHOD
Image.ILBM.decode

SYNTAX
object decode(string data)
object decode(array _decoded)
object decode(array __decoded)

DESCRIPTION
Decodes ILBM data and creates an image object.

RETURNS
the decoded image as an image object

NOTE
This function may throw errors upon illegal ILBM data. This function uses __decode and _decode internally.

SEE ALSO
encode

METHOD
Image.ILBM.encode

SYNTAX
string encode(object image)
string encode(object image,  mapping options)

DESCRIPTION
Encodes an ILBM image.

The options argument may be a mapping containing zero or more encoding options:

normal options:
"alpha":image object
Use this image as mask
(Note: ILBM mask is boolean.
The values are calculated by (r+2g+b)/4>=128.)

"palette":colortable object Use this as palette for pseudocolor encoding

METHOD
Image.ILBM._decode

SYNTAX
array _decode(string|array data)

DESCRIPTION
Decode an ILBM image file.

Result is a mapping,

([
"image": object image,

... more ... ])

image is the stored image.

METHOD
Image.ILBM.__decode

SYNTAX
array __decode();

DESCRIPTION
Decodes an ILBM image structure down to chunks and

({int xsize,int ysize,      // 0: size of image drawing area
string bitmapheader,      // 2: BMHD chunk
void|string colortable,   // 3: opt. colortable chunk (CMAP)
void|string colortable,   // 4: opt. colormode chunk (CAMG)
string body,              // 5: BODY chunk
mapping more_chunks})     // 6: mapping with other chunks

RETURNS
the above array

NOTE
May throw errors if the ILBM header is incomplete or illegal.

12.16 Image.PCX

DESCRIPTION

METHOD
Image.PCX.decode

SYNTAX
object decode(string data)

DESCRIPTION
Decodes a PCX image.

NOTE
Throws upon error in data.

METHOD
Image.PCX.encode,
Image.PCX._encode

SYNTAX
string encode(object image)
string encode(object image,  mapping options)
string _encode(object image)
string _encode(object image,  mapping options)

DESCRIPTION
Encodes a PCX image. The _encode and the encode functions are identical

The options argument may be a mapping containing zero or more encoding options:

normal options:
"raw":1
Do not RLE encode the image
"dpy":int
"xdpy":int
"ydpy":int
Image resolution (in pixels/inch, integer numbers)
"xoffset":int
"yoffset":int
Image offset (not used by most programs, but gimp uses it)

METHOD
Image.PCX._decode

SYNTAX
mapping _decode(string data)

DESCRIPTION
Decodes a PCX image to a mapping.

NOTE
Throws upon error in data.

12.17 Image.PNG

DESCRIPTION

NOTE
This module uses zlib.

METHOD
Image.PNG.decode

SYNTAX
object decode(string data)
object decode(string data,  mapping options)

DESCRIPTION
Decodes a PNG image.

The options argument may be a mapping containing zero or more encoding options:


NOTE
Throws upon error in data.

METHOD
Image.PNG.encode

SYNTAX
string encode(object image)
string encode(object image,  mapping options)

DESCRIPTION
Encodes a PNG image.

The options argument may be a mapping containing zero or more encoding options:

normal options:
"alpha":image object
Use this image as alpha channel
(Note: PNG alpha channel is grey.
The values are calculated by (r+2g+b)/4.)

"palette":colortable object Use this as palette for pseudocolor encoding (Note: encoding with alpha channel and pseudocolor at the same time are not supported)

NOTE
Please read some about PNG files.

METHOD
Image.PNG._chunk

SYNTAX
string _chunk(string type, string data)

DESCRIPTION
Encodes a PNG chunk.

NOTE
Please read about the PNG file format.

METHOD
Image.PNG._decode

SYNTAX
array _decode(string|array data)
array _decode(string|array data, mapping options)

DESCRIPTION
Decode a PNG image file.

Result is a mapping,

([
"image": object image,

... options ... ])

image is the stored image.

Valid entries in options is a superset of the one given to encode:

basic options:

"alpha": object alpha, - alpha channel

"palette": object colortable, - image palette (if non-truecolor)

advanced options:

"background": array(int) color, - suggested background color "background_index": int index, - what index in colortable

"chroma": ({ float white_point_x, float white_point_y, float red_x, float red_y, - CIE x,y chromaticities float green_x, float green_y, float blue_x, float blue_y })

"gamma": float gamma, - gamma

"spalette": object colortable, - suggested palette, for truecolor images "histogram": array(int) hist, - histogram for the image, corresponds to palette index

"physical": ({ int unit, - physical pixel dimension int x,y }) unit 0 means pixels/meter

"sbit": array(int) sbits - significant bits

"text": array(array(string)) text - text information, ({ ({ keyword, data }), ... })

Standard keywords:

Title Short (one line) title or caption for image Author Name of image's creator Description Description of image (possibly long) Copyright Copyright notice Creation Time Time of original image creation Software Software used to create the image Disclaimer Legal disclaimer Warning Warning of nature of content Source Device used to create the image Comment Miscellaneous comment

"time": ({ int year, month, day, - time of last modification hour, minute, second })

wizard options: "compression": int method - compression method (0)

This method can also take options, as a mapping:

advanced options:
"palette": colortable object
- replace the decoded palette with this when
unpacking the image data, if applicable

NOTE
Please read about the PNG file format. This function ignores any checksum errors in the file. A PNG of higher color resolution than the Image module supports (8 bit) will lose that information in the conversion. It throws an error if the image data is erroneous.

METHOD
Image.PNG.__decode

SYNTAX
array __decode(string data)
array __decode(string data,  int dontcheckcrc)

DESCRIPTION
Splits a PNG file into chunks.

Result is an array of arrays, ({ ({ string chunk_type, string data, int crc_ok }), ({ string chunk_type, string data, int crc_ok }) ... })

chunk_type is the type of the chunk, like "IHDR" or "IDAT".

data is the actual chunk data.

crcok is set to 1 if the checksum is ok and dontcheckcrc parameter isn't set.

Returns 0 if it isn't a PNG file.

NOTE
Please read about the PNG file format.

12.18 Image.PNM

DESCRIPTION
This submodule keeps the PNM encode/decode capabilities of the Image module.

PNM is a common image storage format on unix systems, and is a very simple format.

This format doesn't use any color palette.

The format is divided into seven subformats;

P1(PBM) - ascii bitmap (only two colors)
P2(PGM) - ascii greymap (only grey levels)
P3(PPM) - ascii truecolor
P4(PBM) - binary bitmap
P5(PGM) - binary greymap
P6(PPM) - binary truecolor

Simple encoding:
encode,
encode_binary,
encode_ascii

Simple decoding:
decode

Advanced encoding:
encode_P1,
encode_P2,
encode_P3,
encode_P4,
encode_P5,
encode_P6

SEE ALSO
Image, Image.Image and Image.GIF

METHOD
Image.PNM.decode

SYNTAX
object decode(string data)

DESCRIPTION
Decodes PNM (PBM/PGM/PPM) data and creates an image object.

RETURNS
the decoded image as an image object

NOTE
This function may throw errors upon illegal PNM data.

SEE ALSO
encode

METHOD
Image.PNM.encode,
Image.PNM.encode_P1,
Image.PNM.encode_P5,
Image.PNM.encode_ascii,
Image.PNM.encode_P6,
Image.PNM.encode_P2,
Image.PNM.encode_binary,
Image.PNM.encode_P3,
Image.PNM.encode_P4

SYNTAX
string encode(object image)
string encode_binary(object image)
string encode_ascii(object image)
string encode_P1(object image)
string encode_P2(object image)
string encode_P3(object image)
string encode_P4(object image)
string encode_P5(object image)
string encode_P6(object image)

DESCRIPTION
Make a complete PNM file from an image.

encode_binary() and encode_ascii() uses the most optimized encoding for this image (bitmap, grey or truecolor) - P4, P5 or P6 respective P1, P2 or P3.

encode_P1/encode_P4 assumes the image is black and white. Use Image.Image->threshold() or something like Image.Colortable( ({({0,0,0}),({255,255,255})}) )->floyd_steinberg()->map(my_image) to get a black and white image.

encode_P2/encode_P5 assumes the image is greyscale. Use Image.Image->grey() to get a greyscale image.

RETURNS
the encoded image as a string

NOTE
encode() is equal to encode_binary(), but may change in a future release.

SEE ALSO
decode

12.19 Image.PSD

DESCRIPTION

12.20 Image.TGA

DESCRIPTION

METHOD
Image.TGA.decode

SYNTAX
object decode(string data)

DESCRIPTION
Decodes a Targa image.

NOTE
Throws upon error in data.

METHOD
Image.TGA.encode

SYNTAX
string encode(object image)
string encode(object image,  mapping options)

DESCRIPTION
Encodes a Targa image.

The options argument may be a mapping containing zero or more encoding options:

normal options:
"alpha":image object
Use this image as alpha channel
(Note: Targa alpha channel is grey.
The values are calculated by (r+2g+b)/4.)

"raw":1 Do not RLE encode the image

METHOD
Image.TGA._decode

SYNTAX
object _decode(string data)

DESCRIPTION
Decodes a Targa image to a mapping. The mapping follows this format: ([ "image":img_object, "alpha":alpha_channel ])

NOTE
Throws upon error in data.

12.21 Image.XBM

DESCRIPTION

METHOD
Image.XBM.decode

SYNTAX
object decode(string data)

DESCRIPTION
Decodes a XBM image.

NOTE
Throws upon error in data.

METHOD
Image.XBM.encode

SYNTAX
string encode(object image)
string encode(object image,  mapping options)

DESCRIPTION
Encodes a XBM image.

The options argument may be a mapping containing zero or more encoding options.

normal options:
"name":"xbm_image_name"
The name of the XBM. Defaults to 'image'

METHOD
Image.XBM._decode

SYNTAX
object _decode(string data)
object _decode(string data,  mapping options)

DESCRIPTION
Decodes a XBM image to a mapping.

Supported options:
([
"fg":({fgcolor}),    // Foreground color. Default black
"bg":({bgcolor}),    // Background color. Default white
"invert":1,          // Invert the mask
])

NOTE
Throws upon error in data.

12.22 Image.XCF

DESCRIPTION

METHOD
Image.XCF.decode

SYNTAX
object decode(string data)

DESCRIPTION
Decodes a XCF image to a single image object.

NOTE
Throws upon error in data, you will loose quite a lot of information by doing this. See Image.XCF._decode and Image.XCF.__decode

METHOD
Image.XCF.decode_layers

SYNTAX
array(object) decode_layers( string data )

DESCRIPTION
Decodes a XCF image to an array of Image.Layer objects

The layer object have the following extra variables (to be queried using get_misc_value):

image_xres, image_yres, image_colormap, image_guides, image_parasites, name, parasites, visible, active

METHOD
Image.XCF._decode

SYNTAX
mapping _decode(string|object data, mapping|void options)

DESCRIPTION
Decodes a XCF image to a mapping, with at least an 'image' and possibly an 'alpha' object. Data is either a XCF image, or a XCF.GimpImage object structure (as received from __decode)

 Supported options
([
"background":({r,g,b})||Image.Color object
"draw_all_layers":1,
Draw invisible layers as well

"draw_guides":1, Draw the guides

"draw_selection":1, Mark the selection using an overlay

"ignore_unknown_layer_modes":1 Do not asume 'Normal' for unknown layer modes.

"mark_layers":1, Draw an outline around all (drawn) layers

"mark_layer_names":Image.Font object, Write the name of all layers using the font object,

"mark_active_layer":1, Draw an outline around the active layer ])

NOTE
Throws upon error in data. For more information, see Image.XCF.__decode

METHOD
Image.XCF.__decode

SYNTAX
object __decode(string|mapping data,  mapping|void options)

DESCRIPTION
Decodes a XCF image to a Image.XCF.GimpImage object.

Returned structure reference

class GimpImage { int width; int height; int compression; int type; int tattoo_state; float xres = 72.0; float yres = 72.0; int res_unit; Image.Colortable colormap; Image.Colortable meta_colormap; array(Layer) layers = ({}); array(Channel) channels = ({}); array(Guide) guides = ({}); array(Parasite) parasites = ({}); array(Path) paths = ({});

Layer active_layer; Channel active_channel; Channel selection; }

class Layer { string name; int opacity; int type; int mode; int tattoo; mapping flags = ([]); int width, height; int xoffset, yoffset; array (Parasite) parasites; LayerMask mask; Hierarchy image; }

class Channel { string name; int width; int height; int opacity; int r, g, b; int tattoo; Hierarchy image_data; object parent; mapping flags = ([]); array (Parasite) parasites; }

class Hierarchy { Image.Image img; Image.Image alpha; int width; int height; int bpp; }

class Parasite { string name; int flags; string data; }

class Guide { int pos; int vertical; }

class Path { string name; int ptype; int tattoo; int closed; int state; int locked; array (PathPoint) points = ({}); }

class PathPoint { int type; float x; float y; }

METHOD
Image.XCF.___decode

SYNTAX
object ___decode(string|mapping data)

DESCRIPTION
Decodes a XCF image to a mapping.

Structure reference

([ "width":int, "height":int, "type":int, "properties":({ ([ "type":int, "data":string, ]), ... }), "layers":({ ([ "name":string, "width":int, "height":int, "type":type, "properties":({ ([ "type":int, "data":string, ]), ... }), "mask":0 || ([ "name":string, "width":int, "height":int, "properties":({ ([ "type":int, "data":string, ]), ... }), "image_data":([ "bpp":int, "width":int, "height":int, "tiles":({ string, ... }), ]), ]), "image_data":([ "bpp":int, "width":int, "height":int, "tiles":({ string, ... }), ]), ]), ... }), "channels":({ "name":string, "width":int, "height":int, "properties":({ ([ "type":int, "data":string, ]), ... }), "image_data":([ "bpp":int, "width":int, "height":int, "tiles":({ string, ... }), ]), }), ])

12.23 Image.XWD

DESCRIPTION
This submodule keeps the XWD (X Windows Dump) decode capabilities of the Image module.

XWD is the output format for the xwd program.

Simple decoding:
decode

Advanced decoding:
_decode

SEE ALSO
Image, Image.Image, Image.PNM and Image.X

METHOD
Image.XWD.decode

SYNTAX
object decode(string data)

DESCRIPTION
Simple decodes a XWD image file.

METHOD
Image.XWD._decode,
Image.XWD.decode_header

SYNTAX
mapping _decode(string data)
mapping decode_header(string data)

DESCRIPTION
Decodes XWD data and returns the result.

Supported XWD visual classes and encoding formats are TrueColor / ZPixmap DirectColor / ZPixmap PseudoColor / ZPixmap

If someone sends me files of other formats, these formats may be implemented. :) /mirar@idonex.se

RETURNS
the decoded image as an image object

NOTE
This function may throw errors upon illegal or unknown XWD data.

SEE ALSO
decode

12.24 Image.JPEG

DESCRIPTION

NOTE
This module uses libjpeg, a software from Independent JPEG Group.

METHOD
Image.JPEG._decode,
Image.JPEG.decode,
Image.JPEG.decode_header

SYNTAX
object decode(string data)
object decode(string data,  mapping options)
mapping _decode(string data)
mapping _decode(string data,  mapping options)
mapping decode_header(string data)

DESCRIPTION
Decodes a JPEG image. The simple decode function simply gives the image object, the other functions gives a mapping of information (see below)

The options argument may be a mapping containing zero or more encoding options:

advanced options:
"block_smoothing":0|1
Do interblock smoothing. Default is on (1).
"fancy_upsampling":0|1
Do fancy upsampling of chroma components.
Default is on (1).
"method":JPEG.IFAST|JPEG.ISLOW|JPEG.FLOAT|JPEG.DEFAULT|JPEG.FASTEST
DCT method to use.
DEFAULT and FASTEST is from the jpeg library,
probably ISLOW and IFAST respective.

wizard options: "scale_num":1.. "scale_denom":1.. Rescale the image when read from JPEG data. My (Mirar) version (6a) of jpeglib can only handle 1/1, 1/2, 1/4 and 1/8.

_decode and decode_header gives a mapping as result, with this content:

"xsize":int
"ysize":int
size of image
"xdpi":float
"ydpi":float
image dpi, if known
"type":"image/jpeg"
file type information as MIME type

JPEG specific: "num_compontents":int number of channels in JPEG image "color_space":"GRAYSCALE"|"RGB"|"YUV"|"CMYK"|"YCCK"|"UNKNOWN" color space of JPEG image "density_unit":int "x_density":int "y_density":int density of image; unit is 1:dpi 2:dpcm 0:no units "adobe_marker":0|1 if the file has an adobe marker

NOTE
Please read some about JPEG files.

METHOD
Image.JPEG.encode

SYNTAX
string encode(object image)
string encode(object image,  mapping options)

DESCRIPTION
Encodes a JPEG image.

The options argument may be a mapping containing zero or more encoding options:

normal options:
"quality":0..100
Set quality of result. Default is 75.
"optimize":0|1
Optimize Huffman table. Default is on (1) for
images smaller than 50kpixels.
"progressive":0|1
Make a progressive JPEG. Default is off.

advanced options: "smooth":1..100 Smooth input. Value is strength. "method":JPEG.IFAST|JPEG.ISLOW|JPEG.FLOAT|JPEG.DEFAULT|JPEG.FASTEST DCT method to use. DEFAULT and FASTEST is from the jpeg library, probably ISLOW and IFAST respective.

"density_unit":int "x_density":int "y_density":int density of image; unit is 1:dpi 2:dpcm 0:no units

wizard options: "baseline":0|1 Force baseline output. Useful for quality<25. Default is on for quality<25. "quant_tables":mapping(int,array(array(int))) Tune quantisation tables manually.

NOTE
Please read some about JPEG files. A quality setting of 100 does not mean the result is lossless.

12.25 Image.TIFF

DESCRIPTION

METHOD
Image.TIFF.decode

SYNTAX
object decode(string data)

DESCRIPTION
Decodes a TIFF image.

NOTE
Throws upon error in data.

METHOD
Image.TIFF.encode,
Image.TIFF._encode

SYNTAX
string encode(object image)
string encode(object image,  mapping options)
string _encode(object image)
string _encode(object image,  mapping options)

DESCRIPTION
encode and _encode are identical.

The options argument may be a mapping containing zero or more encoding options:

normal options:
"compression":Image.TIFF.COMPRESSION_*,
"name":"an image name",
"comment":"an image comment",
"alpha":An alpha channel,
"dpy":Dots per inch (as a float),
"xdpy":Horizontal dots per inch (as a float),
"ydpy":Vertical dots per inch (as a float),

METHOD
Image.TIFF._decode

SYNTAX
mapping _decode(string data)

DESCRIPTION
Decodes a TIFF image to a mapping with at least the members image and alpha.

NOTE
Throws upon error in data.

12.26 Image.TTF

DESCRIPTION
This module adds TTF (Truetype font) capability to the Image module.

NOTE
This module needs the libttf "Freetype" library

METHOD
Image.TTF.`

SYNTAX
object `()(string filename)
object `()(string filename, mapping options)

DESCRIPTION
Makes a new TTF Face object.

ARGUMENTS
argument(s)description
string filename
The filename of the TTF font or the TTC font collection.
mapping options
advanced options:
"face":int
If opening a font collection,  '.TTC',
this is used to get other fonts than the first.

RETURNS
0 if failed.

12.26.1 Image.TTF.Face

CLASS
Image.TTF.Face

DESCRIPTION
This represents instances of TTF Faces.

METHOD
Image.TTF.Face.flush

SYNTAX
object flush()

DESCRIPTION
This flushes all cached information. Might be used to save memory - the face information is read back from disk upon need.

RETURNS
the called object

METHOD
Image.TTF.Face.names,
Image.TTF.Face._names

SYNTAX
mapping names()
array(array) _names()

DESCRIPTION
Gives back the names or the complete name-list of this face.

The result from names() is a mapping, which has any or all of these indices:

"copyright":   ("Copyright the Foo Corporation...bla bla")
"family":      ("My Little Font")
"style":       ("Bold")
"full":        ("Foo: My Little Font: 1998")
"expose":      ("My Little Font Bold")
"version":     ("June 1, 1998; 1.00, ...")
"postscript":  ("MyLittleFont-Bold")
"trademark":   ("MyLittleFont is a registered...bla bla")

This is extracted from the information from _names(), and fit into pike-strings using unicode or iso-8859-1, if possible.

The result from _names() is a matrix, on this form:

({ ({ int platform, encoding, language, id, string name }),
({ int platform, encoding, language, id, string name }),
...
})

RETURNS
the name as a mapping to string or the names as a matrix

NOTE
To use the values from _names(), check the TrueType standard documentation.

METHOD
Image.TTF.Face.properties

SYNTAX
mapping properties()

DESCRIPTION
This gives back a structure of the face's properties. Most of this stuff is information you can skip.

The most interesting item to look at may be ->num_Faces, which describes the number of faces in a .TTC font collection.

RETURNS
a mapping of a lot of properties

METHOD
Image.TTF.Face.`

SYNTAX
object `()()

DESCRIPTION
This instantiates the face for normal usage - to convert font data to images.

RETURNS
a Image.TTF.FaceInstance object.

12.26.2 Image.TTF.FaceInstance

CLASS
Image.TTF.FaceInstance

DESCRIPTION
This is the instance of a face, with geometrics, encodings and stuff.

METHOD
Image.TTF.FaceInstance.create

SYNTAX
void create(object face)

DESCRIPTION
creates a new Instance from a face.

12.27 Image.XFace

DESCRIPTION

NOTE
This module uses libgmp.

METHOD
Image.XFace.decode

SYNTAX
object decode(string data)
object decode(string data,  mapping options)

DESCRIPTION
Decodes an X-Face image.

The options argument may be a mapping containing zero options.

METHOD
Image.XFace.decode_header

SYNTAX
object decode_header(string data)
object decode_header(string data,  mapping options)

DESCRIPTION
Decodes an X-Face image header.

"xsize":int
"ysize":int
size of image
"type":"image/x-xface"
file type information

The options argument may be a mapping containing zero options.

NOTE
There aint no such thing as a X-Face image header. This stuff tells the characteristics of an X-Face image.

METHOD
Image.XFace.encode

SYNTAX
string encode(object img)
string encode(object img,  mapping options)

DESCRIPTION
Encodes an X-Face image.

The img argument must be an image of the dimensions 48 by 48 pixels. All non-black pixels will be considered white.

The options argument may be a mapping containing zero options.


Previous chapter To contents Next chapter