Imager::APIRef(3pm)
π Imager::APIRef(3pm) π
(User Contributed Perl Documentation)
β¨ NAME β¨
Imager::APIRef β Imager's C API - reference.
π¦ SYNOPSIS π¦
Okay bestie, this synopsis is a whole little C API mood board β every line is exactly as the page lays it out, no cap:
i_color color;
color.rgba.r = 255; color.rgba.g = 0; color.rgba.b = 255;
double x[] = { ... };
double y[] = { ... };
i_polygon_t poly;
poly.count = sizeof(x) / sizeof(*x);
poly.x = x;
poly.y = y;
# Blit tools
# Data Types
i_img *img;
i_color black;
black.rgba.r = black.rgba.g = black.rgba.b = black.rgba.a = 0;
i_fill_t *fill;
i_img_dim x, y;
i_img_dim_u limit;
printf("left %" i_DF "\n", i_DFc(x));
printf("point (" i_DFp ")\n", i_DFcp(x, y));
# Drawing
i_arc(im, 50, 50, 20, 45, 135, &color);
i_arc_cfill(im, 50, 50, 35, 90, 135, fill);
i_arc_aa(im, 50, 50, 35, 90, 135, &color);
i_arc_aa_cfill(im, 50, 50, 35, 90, 135, fill);
i_circle_aa(im, 50, 50, 45, &color);
i_box(im, 0, 0, im->xsize-1, im->ysize-1, &color).
i_box_filled(im, 0, 0, im->xsize-1, im->ysize-1, &color);
i_box_cfill(im, 0, 0, im->xsize-1, im->ysize-1, fill);
i_flood_fill(im, 50, 50, &color);
i_flood_cfill(im, 50, 50, fill);
i_flood_fill_border(im, 50, 50, &color, &border);
i_flood_cfill_border(im, 50, 50, fill, border);
i_poly_poly_aa(im, 1, &poly, mode, color);
i_poly_aa_m(im, count, x, y, mode, color);
i_poly_poly_aa_cfill(im, 1, &poly, mode, fill);
i_poly_aa_cfill(im, count, x, y, mode, fill);
# Error handling
im_clear_error(aIMCTX);
i_clear_error();
i_push_error(0, "Yep, it's broken");
i_push_error(errno, "Error writing");
im_push_error(aIMCTX, 0, "Something is wrong");
va_args args;
va_start(args, lastarg);
im_push_errorvf(ctx, code, format, args);
i_push_errorf(errno, "Cannot open file %s: %d", filename, errno);
im_push_errorf(aIMCTX, errno, "Cannot open file %s: %d", filename, errno);
# Files
im_set_image_file_limits(aIMCTX, 500, 500, 1000000);
i_set_image_file_limits(500, 500, 1000000);
im_get_image_file_limits(aIMCTX, &width, &height, &bytes)
i_get_image_file_limits(&width, &height, &bytes)
im_int_check_image_file_limits(aIMCTX, width, height, channels, sizeof(i_sample_t))
i_int_check_image_file_limits(width, height, channels, sizeof(i_sample_t))
# Fills
i_fill_t *fill = i_new_fill_solidf(&fcolor, combine);
i_fill_t *fill = i_new_fill_solid(&color, combine);
i_fill_t *fill = i_new_fill_hatch(&fg_color, &bg_color, combine, hatch, custom_hatch, dx, dy);
i_fill_t *fill = i_new_fill_hatchf(&fg_fcolor, &bg_fcolor, combine, hatch, custom_hatch, dx, dy);
i_fill_t *fill = i_new_fill_image(src_img, matrix, x_offset, y_offset, combine);
fill = i_new_fill_fount(0, 0, 100, 100, i_ft_linear, i_ft_linear,
i_fr_triangle, 0, i_fts_grid, 9, 1, segs);
i_fill_destroy(fill);
# I/O Layers
ssize_t count = i_io_peekn(ig, buffer, sizeof(buffer));
ssize_t result = i_io_write(io, buffer, size)
char buffer[BUFSIZ]
ssize_t len = i_io_gets(buffer, sizeof(buffer), '\n');
io_glue_destroy(ig);
# Image
# Image creation/destruction
i_img *img = i_sametype(src, width, height);
i_img *img = i_sametype_chans(src, width, height, channels);
i_img *img = im_img_16_new(aIMCTX, width, height, channels);
i_img *img = i_img_16_new(width, height, channels);
i_img *img = im_img_8_new(aIMCTX, width, height, channels);
i_img *img = i_img_8_new(width, height, channels);
i_img *img = im_img_double_new(aIMCTX, width, height, channels);
i_img *img = i_img_double_new(width, height, channels);
i_img *img = im_img_pal_new(aIMCTX, width, height, channels, max_palette_size)
i_img *img = i_img_pal_new(width, height, channels, max_palette_size)
i_img_destroy(img)
# Image Implementation
i_img *im = im_img_alloc(aIMCTX);
i_img *im = i_img_alloc();
im_img_init(aIMCTX, im);
i_img_init(im);
# Image Information
// only channel 0 writable
i_img_setmask(img, 0x01);
int mask = i_img_getmask(img);
int channels = i_img_getchannels(img);
i_img_dim width = i_img_get_width(im);
i_img_dim height = i_img_get_height(im);
i_color_model_t cm = i_img_color_model(im);
int alpha_channel;
int has_alpha = i_img_alpha_channel(im, &alpha_channel);
int color_channels = i_img_color_channels(im);
# Image quantization
# Logging
# mutex
i_mutex_t mutex;
# Mutex functions
i_mutex_t m = i_mutex_new();
i_mutex_destroy(m);
i_mutex_lock(m);
i_mutex_unlock(m);
# Paletted images
# Tags
i_tags_set(&img->tags, "i_comment", -1);
i_tags_setn(&img->tags, "i_xres", 204);
i_tags_setn(&img->tags, "i_yres", 196);
πΈ DESCRIPTION πΈ
π«Ά Blit tools π«Ά
i_render_color(r, x, y, width, source, color)β Render the given color with the coverage specified bysource[0]tosource[width-1].
Renders in normal combine mode.
i_render_delete(r)β Release ani_renderobject.i_render_fill(r, x, y, width, source, fill)β Render the given fill with the coverage insource[0]throughsource[width-1].i_render_line(r, x, y, width, source, fill)β Render the given fill with the coverage insource[0]throughsource[width-1].i_render_linef(r, x, y, width, source, fill)β Render the given fill with the coverage insource[0]throughsource[width-1].i_render_new(im, width)β Allocate a newi_renderobject and initialize it.
π¦ Data Types π¦
π
i_img
i_img *img;
This is Imager's image type.
It contains the following members:
channelsβ the number of channels in the imagexsize,ysizeβ the width and height of the image in pixelsbytesβ the number of bytes used to store the image data. Undefined where virtual is non-zero.ch_maskβ a mask of writable channels. eg. if this is 6 then only channels 1 and 2 are writable. There may be bits set for which there are no channels in the image.bitsβ the number of bits stored per sample. Should be one ofi_8_bits,i_16_bits,i_double_bits.typeβ eitheri_direct_typefor direct color images, ori_palette_typefor paletted images.isvirtualβ if zero then this image is-self contained. If non-zero then this image could be an interface to some other implementation.idataβ the image data. This should not be directly accessed. A new image implementation can use this to store its image data.i_img_destroy()willmyfree()this pointer if it's non-null.tagsβ a structure storing the image's tags. This should only be accessed via thei_tags_*()functions.ext_dataβ a pointer for use internal to an image implementation. This should be freed by the image's destroy handler.im_dataβ data internal to Imager. This is initialized byi_img_init().i_f_ppix,i_f_ppixf,i_f_plin,i_f_plinf,i_f_gpix,i_f_gpixf,i_f_glin,i_f_glinf,i_f_gsamp,i_f_gampfβ implementations for each of the required image functions. An image implementation should initialize these between callingi_img_alloc()andi_img_init().i_f_gpal,i_f_ppal,i_f_addcolors,i_f_getcolors,i_f_colorcount,i_f_maxcolors,i_f_findcolor,i_f_setcolorsβ implementations for each paletted image function.i_f_destroyβ custom image destruction function. This should be used to release memory if necessary.i_f_gsamp_bitsβ implementsi_gsamp_bits()for this image.i_f_psamp_bitsβ implementsi_psamp_bits()for this image.i_f_psampβ implementspsamp()for this image.i_f_psampfβ implementspsamp()for this image.im_dataβ image specific data internal to Imager.contextβ the Imager API context this image belongs to.
π i_color
i_color black;
black.rgba.r = black.rgba.g = black.rgba.b = black.rgba.a = 0;
Type for 8-bit/sample color.
Samples as per;
i_color c;
i_color is a union of:
grayβ contains a single elementgray_color, eg.c.gray.gray_colorrgbβ contains three elementsr,g,b, eg.c.rgb.rrgbaβ contains four elementsr,g,b,a, eg.c.rgba.acmykβ contains four elementsc,m,y,k, eg.c.cmyk.y. Note that Imager never uses CMYK colors except when reading/writing files.channelsβ an array of four channels, egc.channels[2].
π i_fcolor
This is the double/sample color type.
Its layout exactly corresponds to i_color.
π i_fill_t
i_fill_t *fill;
This is the "abstract" base type for Imager's fill types.
Unless you're implementing a new fill type you'll typically treat this as an opaque type.
π i_poly_fill_mode_t
Control how polygons are filled. Has the following values:
i_pfm_evenoddβ simple even-odd fills.i_pfm_nonzeroβ non-zero winding rule fills.
π§ i_polygon_t
Represents a polygon. Has the following members:
x,yβ arrays of x and y locations of vertices.countβ the number of entries in thexandyarrays.
π im_context_t
Imager's per-thread context.
β im_slot_t
Represents a slot in the context object.
π¦ i_img_dim
i_img_dim x, y;
A signed integer type that represents an image dimension or ordinate.
May be larger than int on some platforms.
π i_img_dim_u
i_img_dim_u limit;
An unsigned variant of i_img_dim.
π₯ i_color_model_t
Returned by i_img_color_model(im) to indicate the color model of the image.
An enumerated type with the following possible values:
icm_unknownβ the image has no usable color data. In future versions of Imager this will be returned in a few limited cases, eg. when the source image is CMYK and the user has requested no color translation is done.icm_grayβ gray scale with no alpha channel.icm_gray_alphaβ gray scale with an alpha channel.icm_rgbβ RGBicm_rgb_alphaβ RGB with an alpha channel.
π i_DF
printf("left %" i_DF "\n", i_DFc(x));
First up, the dimension-formatting besties π β i_DF is a constant string you can pass to printf()-style functions to format i_img_dim values after they've been cast with i_DFc(). It does not include the leading %. periodt π
i_DFcβ casts ani_img_dimvalue to a type for use with thei_DFformat string. slay.i_DFcpβ casts twoi_img_dimvalues for use with thei_DF(ori_DFp) format. two-for-one energy.i_DFpβ formats a pair ofi_img_dimvalues. This one does include the leading%.
printf("point (" i_DFp ")\n", i_DFcp(x, y));
Drawing π¨β¨
i_arc(im, x, y, rad, d1, d2, color)β fills an arc centered at(x,y)with radiusrad, covering the range of angles in degrees fromd1tod2, usingcolor. arc core π
i_arc(im, 50, 50, 20, 45, 135, &color);
i_arc_aa(im, x, y, rad, d1, d2, color)β anti-alias fills an arc centered at(x,y)with radiusrad, covering the range of angles in degrees fromd1tod2, usingcolor. smooth vibes β¨
i_arc_aa(im, 50, 50, 35, 90, 135, &color);
i_arc_aa_cfill(im, x, y, rad, d1, d2, fill)β anti-alias fills an arc centered at(x,y)with radiusrad, covering the range of angles in degrees fromd1tod2, using thefillobject. fill moment
i_arc_aa_cfill(im, 50, 50, 35, 90, 135, fill);
i_arc_cfill(im, x, y, rad, d1, d2, fill)β fills an arc centered at(x,y)with radiusrad, covering the range of angles in degrees fromd1tod2, using thefillobject. filled and iconic
i_arc_cfill(im, 50, 50, 35, 90, 135, fill);
i_box(im, x1, y1, x2, y2, color)β outlines the box from(x1,y1)to(x2,y2)inclusive withcolor. boxed π
i_box(im, 0, 0, im->xsize-1, im->ysize-1, &color).
i_box_cfill(im, x1, y1, x2, y2, fill)β fills the box from(x1,y1)to(x2,y2)inclusive withfill. filled box
i_box_cfill(im, 0, 0, im->xsize-1, im->ysize-1, fill);
i_box_filled(im, x1, y1, x2, y2, color)β fills the box from(x1,y1)to(x2,y2)inclusive withcolor. solid β
i_box_filled(im, 0, 0, im->xsize-1, im->ysize-1, &color);
i_circle_aa(im, x, y, rad, color)β anti-alias fills a circle centered at(x,y)for radiusradwithcolor. circle slay π
i_circle_aa(im, 50, 50, 45, &color);
i_flood_cfill("im", "seedx", "seedy", "fill")β flood fills the 4-connected region starting from the point (seedx,seedy) withfill. Returns false if (seedx,seedy) are outside the image. flood it π
i_flood_cfill(im, 50, 50, fill);
i_flood_cfill_border("im", "seedx", "seedy", "fill", "border")β flood fills the 4-connected region starting from the point (seedx,seedy) withfill, and the fill stops when it reaches pixels of colorborder. Returns false if (seedx,seedy) are outside the image. border patrol π§
i_flood_cfill_border(im, 50, 50, fill, border);
i_flood_fill("im", "seedx", "seedy", "color")β flood fills the 4-connected region starting from the point (seedx,seedy) withcolor. Returns false if (seedx,seedy) are outside the image. flood fill classic
i_flood_fill(im, 50, 50, &color);
i_flood_fill_border("im", "seedx", "seedy", "color", "border")β flood fills the 4-connected region starting from the point (seedx,seedy) withcolor, and the fill stops when it reaches pixels with colorborder. Returns false if (seedx,seedy) are outside the image. stop at the border πi_glin(im, l, r, y, colors)β retrieves(r-l)pixels starting from(l,y)intocolors. Returns the number of pixels retrieved. grab those pixelsi_glinf(im, l, r, y, colors)β retrieves(r-l)pixels starting from(l,y)intocolorsas floating point colors. Returns the number of pixels retrieved. floaty pixels π¦i_gpal(im, left, right, y, indexes)β reads palette indexes for the horizontal line(left, y)to(right-1, y)intoindexes. Returns the number of indexes read. Always returns0for direct color images. palette checki_gpix(im, "x", "y", "color")β retrieves thecolorof the pixel(x,y). Returns0if the pixel was retrieved, or-1if not. pixel peek πi_gpixf(im, "x", "y", "fcolor")β retrieves the color of the pixel(x,y)as a floating point color intofcolor. Returns0if the pixel was retrieved, or-1if not. float pixel peeki_gsamp(im, left, right, y, samples, channels, channel_count)β reads sample values fromimfor the horizontal line(left, y)to(right-1,y)for the channels specified bychannels, an array ofintwithchannel_countelements. IfchannelsisNULLthen the firstchannels_countchannels are retrieved for each pixel. Returns the number of samples read (which should be(right-left) * channel_count). sample squad π§ͺi_gsamp_bg(im, l, r, y, samples, out_channels, background)β likei_gsampf()but applies the source image color over a supplied background color. This is intended for output to image formats that don't support alpha channels. background behaviori_gsamp_bits(im, left, right, y, samples, channels, channel_count, bits)β reads integer samples scaled tobitsbits of precision into theunsigned intarraysamples. Expect this to be slow unlessbits == im->bits. Returns the number of samples copied, or-1on error. Not all image types implement this method. Pushes errors, but does not calli_clear_error(). slow unless matched πi_gsampf(im, left, right, y, samples, channels, channel_count)β reads floating point sample values fromimfor the horizontal line(left, y)to(right-1,y)for the channels specified bychannels, an array ofintwithchannel_countelements. IfchannelsisNULLthen the firstchannel_countchannels are retrieved for each pixel. Returns the number of samples read (which should be(right-left) * channel_count). float samples β¨i_gsampf_bg(im, l, r, y, samples, out_channels, background)β likei_gsampf()but applies the source image color over a supplied background color. This is intended for output to image formats that don't support alpha channels. blend over backgroundi_line("im", "x1", "y1", "x2", "y2", "color", "endp")β draws a line to the image using Bresenham's line drawing algorithm. line legend πimβ image to draw tox1β starting x coordinatey1β starting x coordinatex2β starting x coordinatey2β starting x coordinatecolorβ color to write to imageendpβ endpoint flag (boolean)
i_line_aa("im", "x1", "x2", "y1", "y2", "color", "endp")β anti-alias draws a line from(x1,y1)to(x2, y2)incolor. The point(x2, y2)is drawn only ifendpis set. smooth line πi_plin(im, l, r, y, colors)β sets(r-l)pixels starting from(l,y)using(r-l)values fromcolors. Returns the number of pixels set. put those pixelsi_plinf(im, "left", "right", "fcolors")β sets(right-left)pixels starting from(left,y)using(right-left)floating point colors fromfcolors. Returns the number of pixels set. float write π«Άi_poly_aa_cfill_m(im, count, x, y, mode, fill)β fills a polygon defined by the points specified by thexandyarrays with thefillspecified byfill. polygon fill π₯
i_poly_aa_cfill(im, count, x, y, mode, fill);
i_poly_aa_m(im, count, x, y, mode, color)β fills a polygon defined by the points specified by thexandyarrays with the color specified bycolor. polygon color π¨
i_poly_aa_m(im, count, x, y, mode, color);
i_poly_poly_aa(im, count, polys, mode, color)β fills thecountpolygons defined bypolyswith the color specified bycolor. At least one polygon must be supplied. All polygons must have at least 3 points. poly poly πΈ
i_poly_poly_aa(im, 1, &poly, mode, color);
i_poly_poly_aa_cfill(im, count, polys, mode, fill)β fills thecountpolygons defined bypolyswith the fill specified byfill. At least one polygon must be supplied. All polygons must have at least 3 points. poly fill β
i_poly_poly_aa_cfill(im, 1, &poly, mode, fill);
i_ppal(im, left, right, y, indexes)β writes palette indexes for the horizontal line(left, y)to(right-1, y)fromindexes. Returns the number of indexes written. Always returns0for direct color images. palette writei_ppix(im, x, y, color)β sets the pixel at(x,y)tocolor. Returns0if the pixel was drawn, or-1if not. Does no alpha blending, just copies the channels from the supplied color to the image. pixel put πi_ppixf(im, "x", "y", "fcolor")β sets the pixel at (x,y) to the floating point colorfcolor. Returns0if the pixel was drawn, or-1if not. Does no alpha blending, just copies the channels from the supplied color to the image. float pixel puti_psamp(im, left, right, y, samples, channels, channel_count)β writes sample values fromsamplestoimfor the horizontal line(left, y)to(right-1, y)inclusive for the channels specified bychannels, an array ofintwithchannel_countelements. IfchannelsisNULLthen the firstchannels_countchannels are written to for each pixel. Returns the number of samples written, which should be(right - left) * channel_count. If a channel not in the image is inchannels,leftis negative,leftis outside the image oryis outside the image, returns-1and pushes an error. sample write rules π¨i_psamp_bits(im, left, right, y, samples, channels, channel_count, bits)β writes integer samples scaled tobitsbits of precision from theunsigned intarraysamples. Expect this to be slow unlessbits == im->bits. Returns the number of samples copied, or-1on error. Not all image types implement this method. Pushes errors, but does not calli_clear_error(). bits write πi_psampf(im, left, right, y, samples, channels, channel_count)β writes floating point sample values fromsamplestoimfor the horizontal line(left, y)to(right-1, y)inclusive for the channels specified bychannels, an array ofintwithchannel_countelements. IfchannelsisNULLthen the firstchannels_countchannels are written to for each pixel. Returns the number of samples written, which should be(right - left) * channel_count. If a channel not in the image is inchannels,leftis negative,leftis outside the image oryis outside the image, returns-1and pushes an error. float sample write β¨
π¨ Error handling π¨
i_push_errorf(int code, char const *fmt, ...)β a version ofi_push_error()that doesprintf()-like formatting. Does not support perl specific format codes. fancy error π
i_push_errorf(errno, "Cannot open file %s: %d", filename, errno);
im_clear_error(ctx)β clears the error stack. clean slate energy π«Ά
im_clear_error(aIMCTX);
i_clear_error();
im_clear_error() is the function every Imager function calls before doing literally anything else. Also callable as i_clear_error(). π
im_push_error(ctx, code, message) β an Imager function calls this to push an error message onto the stack. No message is pushed if the stack is full (since this means someone forgot to call i_clear_error(), or that a function that doesn't do error handling is calling function that does.). π
i_push_error(0, "Yep, it's broken");
i_push_error(errno, "Error writing");
im_push_error(aIMCTX, 0, "Something is wrong");
im_push_errorf(ctx, code, char const *fmt, ...) β a version of im_push_error() that does printf() like formatting. It does not support perl specific format codes. β¨
im_push_errorf(aIMCTX, errno, "Cannot open file %s: %d", filename, errno);
im_push_errorvf(ctx, code, format, args) β intended for use by higher level functions, it takes a varargs pointer and a format to produce the finally pushed error message. It does not support perl specific format codes. Also callable as i_push_errorvf(code, format, args). π«Ά
va_args args;
va_start(args, lastarg);
im_push_errorvf(ctx, code, format, args);
ποΈ Files ποΈ
i_get_file_background(im, &bg) β grabs the file write background color tag from the image. If it's not there, bg is set to black. Returns 1 if the i_background tag was found and valid. π
i_get_file_backgroundf(im, &bg) β same mission but retrieves the file write background color tag from the image as a floating point color. Implemented in terms of i_get_file_background(). If it's not there, bg is set to black. Returns 1 if the i_background tag was found and valid. π¦
im_get_image_file_limits(ctx, &width, &height, &bytes) β retrieves the file limits set by i_set_image_file_limits(). π
im_get_image_file_limits(aIMCTX, &width, &height, &bytes)
i_get_image_file_limits(&width, &height, &bytes)
i_img_dim *width, *heightβ the maximum width and height of the image.size_t *bytesβ size in memory of the image in bytes.
Also callable as i_get_image_file_limits(&width, &height, &bytes). πΈ
im_int_check_image_file_limits(width, height, channels, sample_size) β checks the size of a file in memory against the configured image file limits. This also range checks the values to those permitted by Imager and checks for overflows in calculating the size. Returns non-zero if the file is within limits. This function is intended to be called by image file read functions. π₯
im_int_check_image_file_limits(aIMCTX, width, height, channels, sizeof(i_sample_t))
i_int_check_image_file_limits(width, height, channels, sizeof(i_sample_t))
Also callable as i_int_check_image_file_limits(width, height, channels, sizeof(i_sample_t). π
im_set_image_file_limits(ctx, width, height, bytes) β set limits on the sizes of images read by Imager. Setting a limit to 0 means that limit is ignored. Negative limits result in failure. π
im_set_image_file_limits(aIMCTX, 500, 500, 1000000);
i_set_image_file_limits(500, 500, 1000000);
Parameters:
i_img_dim width, heightβ maximum width and height.size_t bytesβ maximum size in memory in bytes. A value of zero sets this limit to one gigabyte.
Returns non-zero on success. Also callable as i_set_image_file_limits(width, height, bytes). β
π¨ Fills π¨
i_new_fill_fount("xa", "ya", "xb", "yb", "type", "repeat", "combine", "super_sample", "ssample_param", "count", "segs") β creates a new general fill which fills with a fountain fill. π
fill = i_new_fill_fount(0, 0, 100, 100, i_ft_linear, i_ft_linear,
i_fr_triangle, 0, i_fts_grid, 9, 1, segs);
i_new_fill_hatch("fg", "bg", "combine", "hatch", "cust_hatch", "dx", "dy") β creates a new hatched fill with the fg color used for the 1 bits in the hatch and bg for the 0 bits. If combine is non-zero alpha values will be combined. π
If cust_hatch is non-NULL it should be a pointer to 8 bytes of the hash definition, with the high-bits to the left.
If cust_hatch is NULL then one of the standard hatches is used.
(dx, dy) are an offset into the hatch which can be used to hatch adjoining areas out of alignment, or to align the origin of a hatch with the side of a filled area. β¨
i_fill_t *fill = i_new_fill_hatch(&fg_color, &bg_color, combine, hatch, custom_hatch, dx, dy);
i_new_fill_hatchf("fg", "bg", "combine", "hatch", "cust_hatch", "dx", "dy") β creates a new hatched fill with the fg color used for the 1 bits in the hatch and bg for the 0 bits. If combine is non-zero alpha values will be combined. π§
If cust_hatch is non-NULL it should be a pointer to 8 bytes of the hash definition, with the high-bits to the left.
If cust_hatch is NULL then one of the standard hatches is used.
(dx, dy) are an offset into the hatch which can be used to hatch adjoining areas out of alignment, or to align the origin of a hatch with the side of a filled area. π
i_fill_t *fill = i_new_fill_hatchf(&fg_fcolor, &bg_fcolor, combine, hatch, custom_hatch, dx, dy);
i_new_fill_image("im", "matrix", "xoff", "yoff", "combine") β create an image based fill. matrix is an array of 9 doubles representing a transformation matrix. xoff and yoff are the offset into the image to start filling from. π
i_fill_t *fill = i_new_fill_image(src_img, matrix, x_offset, y_offset, combine);
i_new_fill_solid(color, combine) β create a solid fill based on an 8-bit color. If combine is non-zero then alpha values will be combined. π
i_fill_t *fill = i_new_fill_solid(&color, combine);
i_new_fill_solidf(color, combine) β create a solid fill based on a float color. If combine is non-zero then alpha values will be combined. π
i_fill_t *fill = i_new_fill_solidf(&fcolor, combine);
i_fill_destroy(fill) β call to destroy any fill object. π
i_fill_destroy(fill);
π I/O Layers π
im_io_new_bufchain(ctx) β returns a new io_glue object that has the 'empty' source and can be written to and read from later (like a pseudo file). Also callable as io_new_bufchain(). πΈ
im_io_new_buffer(ctx, data, length) β returns a new io_glue object that has the source defined as reading from specified buffer. Note that the buffer is not copied. π«Ά
ctxβ an Imager context objectdataβ buffer to read fromlengthβ length of buffer
Also callable as io_new_buffer(data, length. π
im_io_new_cb(ctx, p, read_cb, write_cb, seek_cb, close_cb, destroy_cb) β create a new I/O layer object that calls your supplied callbacks. In general the callbacks should behave like the corresponding POSIX primitives. π₯
read_cb(p, buffer, length)should read up tolengthbytes intobufferand return the number of bytes read. At end of file, return0. On error, return-1.write_cb(p, buffer, length)should write up tolengthbytes frombufferand return the number of bytes written. A return value<= 0will be treated as an error.seekcb(p, offset, whence)should seek and return the new offset.close_cb(p)should return0on success,-1on failure.destroy_cb(p)should release any memory specific to your callback handlers.
Also callable as io_new_cb(p, readcb, writecb, seekcb, closecb, destroycb). β
im_io_new_fd(ctx, file) β returns a new io_glue object that has the source defined as reading from specified file descriptor. Note that the interface to receiving data from the io_glue callbacks hasn't been done yet. π
ctxβ an Imager context objectfileβ file descriptor to read/write from
Also callable as io_new_fd(file). π
i_io_close(io) β flush any pending output and perform the close action for the stream. Returns 0 on success. β¨
i_io_flush(io) β flush any buffered output. Returns true on success. π¦
i_io_getc(ig) β a macro to read a single byte from a buffered I/O glue object. Returns EOF on failure, or a byte. π
i_io_gets(ig, buffer, size, end_of_line) β read up to size-1 bytes from the stream ig into buffer. If the byte end_of_line is seen then no further bytes will be read. Returns the number of bytes read. Always NUL terminates the buffer. π
char buffer[BUFSIZ]
ssize_t len = i_io_gets(buffer, sizeof(buffer), '\n');
i_io_peekc(ig) β read the next character from the stream without advancing the stream. On error or end of file, return EOF. For unbuffered streams a single character buffer will be setup. π§
i_io_peekn(ig, buffer, size) β buffer at least size (at most ig->buf_size) bytes of data from the stream and return size bytes of it to the caller in buffer. This ignores the buffered state of the stream, and will always setup buffering if needed. If no type parameter is provided to Imager::read() or Imager::read_multi(), Imager will call i_io_peekn() when probing for the file format. Returns -1 on error, 0 if there is no data before EOF, or the number of bytes read into buffer. π₯
ssize_t count = i_io_peekn(ig, buffer, sizeof(buffer));
i_io_putc(ig, c) β write a single character to the stream. On success return c, on error returns EOF. π
i_io_read(io, buffer, size) β read up to size bytes from the stream io into buffer. Returns the number of bytes read. Returns 0 on end of file. Returns -1 on error. π
i_io_seek(io, offset, whence) β seek within the stream. Acts like perl's seek. π
i_io_set_buffered(io, buffered) β set the buffering mode of the stream. If you switch buffering off on a stream with buffering on: π
- any buffered output will be flushed.
- any existing buffered input will be consumed before reads become unbuffered.
Returns true on success. This may fail if any buffered output cannot be flushed. π
i_io_write(io, buffer, size) β write to the given I/O stream. Returns the number of bytes written. πΈ
ssize_t result = i_io_write(io, buffer, size)
io_slurp(ig, c)
Okay so this one takes the source that the io_glue is bound to, allocates space for a return buffer, and gives you the entire content back in one single buffer. π Big important note: this only works for io_glue objects created by io_new_bufchain(). It's useful for saving to scalars and such.
Args:
igβ io_glue objectcβ pointer to a pointer to where data should be copied to
char *data;
size_t size = io_slurp(ig, &data);
... do something with the data ...
myfree(data);
π¨ Heads up, bestie:io_slurp()will abort the program if the supplied I/O layer is not fromio_new_bufchain(). No cap.
io_glue_destroy(ig)
io_glue_destroy(ig);
Destroys an io_glue object. It should clean up all related buffers. π§Ή
igβ io_glue object to destroy.
π Image π
i_copy(source)
Creates a new image that is a copy of the image source. β¨
Tags are not copied β only the image data.
Returns: i_img *
i_copyto("dest", "src", "x1", "y1", "x2", "y2", "tx", "ty")
Copies image data from the area (x1,y1)-[x2,y2] in the source image to a rectangle the same size with it's top-left corner at (tx,ty) in the destination image. π―
If x1 > x2 or y1 > y2, then the corresponding co-ordinates are swapped.
i_copyto_trans("im", "src", "x1", "y1", "x2", "y2", "tx", "ty", "trans")
(x1,y1) (x2,y2) specifies the region to copy β in the source coordinates. (tx,ty) specifies the upper left corner for the target image. Pass NULL in trans for non transparent i_colors. π«Ά
i_img_info(im, info)
Returns image information. π
imβ Image pointerinfoβ pointer to array to return data
info is an array of 4 integers with these values:
info[0] - width
info[1] - height
info[2] - channels
info[3] - channel mask
i_rubthru("im", "src", "tx", "ty", "src_minx", "src_miny", "src_maxx", "src_maxy")
Takes the sub image src[src_minx, src_maxx)[src_miny, src_maxy)]> and overlays it at (tx,ty) on the image object. π¦
The alpha channel of each pixel in src is used to control how much the existing color in im is replaced. If it is 255, then the color is completely replaced. If it is 0, then the original color is left unmodified.
π Image creation/destruction π
i_sametype("im", "xsize", "ysize")
i_img *img = i_sametype(src, width, height);
Returns an image of the same type β same sample size, channels, paletted/direct. π
For paletted images the palette is copied from the source.
i_sametype_chans("im", "xsize", "ysize", "channels")
i_img *img = i_sametype_chans(src, width, height, channels);
Returns an image of the same type β same sample size. β¨
For paletted images the equivalent direct type is returned.
im_img_16_new(ctx, x, y, ch)
i_img *img = im_img_16_new(aIMCTX, width, height, channels);
i_img *img = i_img_16_new(width, height, channels);
Creates a new 16-bit/sample image. π
Returns the image on success, or NULL on failure.
Also callable as i_img_16_new(x, y, ch).
im_img_8_new(ctx, x, y, ch)
i_img *img = im_img_8_new(aIMCTX, width, height, channels);
i_img *img = i_img_8_new(width, height, channels);
Creates a new image object x pixels wide and y pixels high with ch channels. π¨
im_img_double_new(ctx, x, y, ch)
i_img *img = im_img_double_new(aIMCTX, width, height, channels);
i_img *img = i_img_double_new(width, height, channels);
Creates a new double per sample image. π
Also callable as i_img_double_new(width, height, channels).
im_img_pal_new(ctx, "x", "y", "channels", "maxpal")
i_img *img = im_img_pal_new(aIMCTX, width, height, channels, max_palette_size)
i_img *img = i_img_pal_new(width, height, channels, max_palette_size)
Creates a new paletted image of the supplied dimensions. π
maxpal is the maximum palette size and should normally be 256.
Returns a new image or NULL on failure.
Also callable as i_img_pal_new(width, height, channels, max_palette_size).
i_img_destroy("img")
i_img_destroy(img)
Destroys an image object. π
πΈ Image Implementation πΈ
im_img_alloc(aIMCTX)
i_img *im = im_img_alloc(aIMCTX);
i_img *im = i_img_alloc();
Allocates a new i_img structure. π§
When implementing a new image type, perform the following steps in your image object creation function:
- allocate the image with
i_img_alloc(). - initialize any function pointers or other data as needed β you can overwrite the whole block if you need to.
- initialize Imager's internal data by calling
i_img_init()on the image object.
im_img_init(aIMCTX, image)
im_img_init(aIMCTX, im);
i_img_init(im);
Imager internal initialization of images. π«§
See im_img_alloc(aIMCTX) for more information.
β¨ Image Information β¨
i_img_alpha_channel(im, &channel)
int alpha_channel;
int has_alpha = i_img_alpha_channel(im, &alpha_channel);
Works out the alpha channel for an image. π
If the image has an alpha channel, sets *channel to the alpha channel index and returns non-zero.
If the image has no alpha channel, returns zero and *channel is not modified.
channel may be NULL.
i_img_color_channels(im)
int color_channels = i_img_color_channels(im);
Returns the number of color channels in the image. For now this is always 1 (for grayscale) or 3 (for RGB), but may be 0 in some special cases in a future release of Imager. π
i_img_color_model(im)
i_color_model_t cm = i_img_color_model(im);
Returns the color model for the image. π¨
A future version of Imager will allow for images with extra channels beyond gray/rgb and alpha.
i_img_get_height("im")
i_img_dim height = i_img_get_height(im);
Returns the height in pixels of the image. π
i_img_get_width("im")
i_img_dim width = i_img_get_width(im);
Returns the width in pixels of the image. π
i_img_getchannels("im")
int channels = i_img_getchannels(img);
Gets the number of channels in im. π«
i_img_getmask("im")
int mask = i_img_getmask(img);
Gets the image channel mask for im. π
i_img_has_alpha("im")
Returns true if the image has an alpha channel. β
i_img_is_monochrome(img, &zero_is_white)
Tests an image to check it meets our monochrome tests. π€π€
The idea is that a file writer can use this to test where it should write the image in whatever bi-level format it uses, eg. pbm for pnm.
For performance of encoders we require monochrome images:
- be paletted
- have a palette of two colors, containing only
(0,0,0)and(255,255,255)in either order.
zero_is_white is set to non-zero if the first palette entry is white.
i_img_setmask("im", "ch_mask")
// only channel 0 writable
i_img_setmask(img, 0x01);
Sets the image channel mask for im to ch_mask. ποΈ
The image channel mask gives some control over which channels can be written to in the image.
π₯ Image quantization π₯
i_quant_makemap("quant", "imgs", "count")
Analyzes the count images in imgs according to the rules in quant to build a color map β optimal or not depending on quant->make_colors. π§
i_quant_translate("quant", "img")
Quantizes the image given the palette in quant. π―
On success returns a pointer to a memory block of img->xsize * img->ysize i_palidx entries.
On failure returns NULL.
You should call myfree() on the returned block when you're done with it.
This function will fail if the supplied palette contains no colors.
i_quant_transparent("quant", "data", "img", "trans_index")
Dithers the alpha channel on img into the palette indexes in data. Pixels to be transparent are replaced with trans_pixel. π«§
The method used depends on the tr_* members of quant.
π Logging π
i_lhead(file, line)
This is an internal function called by the mm_log() macro. π
i_loog(level, format, ...)
This is an internal function called by the mm_log() macro. π
π mutex π
i_mutex_t
i_mutex_t mutex;
Opaque type for Imager's mutex API. π
π¦ Mutex functions π¦
i_mutex_new()
i_mutex_t m = i_mutex_new();
Creates a mutex. β¨
If a critical section cannot be created for whatever reason, Imager will abort.
i_mutex_destroy(m)
i_mutex_destroy(m);
Destroys a mutex. π₯
i_mutex_lock(m)
i_mutex_lock(m);
Locks the mutex, waiting if another thread has the mutex locked. β³
i_mutex_unlock(m)
i_mutex_unlock(m);
Releases the mutex. π
The behavior of releasing a mutex you don't hold is unspecified. So maybe don't, bestie.
π Paletted images π
i_addcolors(im, colors, count)
Adds colors to the image's palette. π¨
On success returns the index of the lowest color added.
On failure returns -1.
Always fails for direct color images.
i_colorcount(im)
Returns the number of colors in the image's palette. π’
Returns -1 for direct images.
i_findcolor(im, color, &entry)
Searches the image's palette for the given color. π
On success sets *entry to the index of the color, and returns true.
On failure returns false.
Always fails on direct color images.
i_getcolors(im, index, colors, count)
Retrieves count colors starting from index in the image's palette. π
On success stores the colors into colors and returns true.
On failure returns false.
Always fails for direct color images.
Fails if there are less than index+count colors in the image's palette.
i_maxcolors(im)
Returns the maximum number of colors the palette can hold for the image. π¨
Returns -1 for direct color images.
i_setcolors(im, index, colors, count)
Sets count colors starting from index in the image's palette. ποΈ
On success returns true.
On failure returns false.
The image must have at least index+count colors in it's palette for this to succeed.
Always fails on direct color images.
π Tags π
i_tags_delbycode(tags, code)
Deletes any tags with the given code. π·οΈ
Returns the number of tags deleted.
i_tags_delbyname(tags, name)
Deletes any tags with the given name. π·οΈ
Returns the number of tags deleted.
i_tags_delete(tags, index)
Deletes a tag by index. βοΈ
Returns true on success.
i_tags_destroy(tags)β yeets the whole tags struct into the void π. Like, it's gone gone. Fun fact:i_img_destroy()is the one that calls this for you, so you usually don't have to.i_tags_find(tags, name, start, &entry)β scavenger hunt time π: looks for a tag with thatname, starting your search at indexstart.
Win = returns true and sets *entry.
Lose = returns false. sad but valid.
i_tags_findn(tags, code, start, &entry)β same scavenger hunt, but you're hunting bycodeinstead ofname, starting at indexstart.
Win = true, and *entry gets set.
Lose = false.
i_tags_get_color(tags, name, code, &value)β pulls out a tag (bynameorcode) and reads it as a color π¨.
Win = sets the i_color *value to that color and returns true.
Lose = false.
i_tags_get_float(tags, name, code, value)β reads a tag as a floating point number, ngl it's a little quirky: if the tag holds a string, that string gets parsed as a float; otherwise the tag's integer value is what you get.
Win = sets *value, returns true.
Lose = false.
i_tags_get_int(tags, name, code, &value)β grab a tag bynameorcodeand read it as an integer π’.
Win = sets the int *value and returns true.
Lose = false.
i_tags_get_string(tags, name, code, value, value_size)β reads a tag (by name or code) as a string, bestie.
Win = copies the string into value, max value_size, returns true.
Lose = false.
Real talk: value_size has to be big enough to hold a string representation of an integer, minimum. Don't skimp.
The copied value is always "NUL" terminated, always always.
i_tags_new(i_img_tags *tags)β sets up a tags struct from scratch β¨. Do not use this if the tags struct has already been used β that's not a vibe.
You're supposed to call this on the tags member of an i_img object when it's created (inside the i_img_*_new() functions).
To tear the contents back down, that's i_tags_destroy()'s job.
i_tags_set(tags, name, data, size)β sets the given tag to the stringdata. The classic:
i_tags_set(&img->tags, "i_comment", -1);
If size is -1, then strlen(data) bytes get stored. cute shortcut π
Heads up: even on failure, if a tag with that name already exists, it gets removed. So it's a "you lose either way" kind of situation for the old tag.
i_tags_set_color(tags, name, code, &value)β stores the given color as a tag with the givennameandcode. simple as that πi_tags_set_float(tags, name, code, value)β literally just the same asi_tags_set_float2(tags, name, code, value, 30). that's the whole thing.i_tags_set_float2(tags, name, code, value, places)β sets the tag (givennameandcode) to the floating pointvalue.
So here's the thing: tags are strings or ints, right? So the value gets converted to a string before it's stored, at the precision you pick with places. π
i_tags_setn("tags", "name", "idata")β sets the given tag to the integeridata. Example era:
i_tags_setn(&img->tags, "i_xres", 204);
i_tags_setn(&img->tags, "i_yres", 196);
Same warning as before, bestie: even on failure, if a tag with that name already exists, it will be removed. π
πΈ Uncategorized functions πΈ
i_utf8_advance(char **p, size_t *len)β grabs a"UTF-8"character out of the stream.
It modifies *p and *len so you can see which characters got consumed.
Important, don't skip: this does not support the extended "UTF-8" encoding that later versions of Perl use. Since this is usually how font drivers implement text output, the strings handed to it shouldn't contain those out of range characters.
Also it does not check that the "UTF-8" character is using the shortest possible representation. Just so you know.
Returns ~0UL on failure. π
im_context_refdec(ctx, where)=section Context objectsβ drops a reference to the context, and releases it if that was the last reference left.
im_context_refdec(aIMCTX, "a description");
im_context_refinc(ctx, where)=section Context objectsβ adds a brand new reference to the context. π«Ά
im_context_refinc(aIMCTX, "a description");
im_context_slot_get(ctx, slot)β fetches whatever value you previously stashed in that slot of the context object. it's giving "checks notes" πim_context_slot_new(destructor)β allocates a fresh context-local-storage slot.
That "desctructor" (yes, spelled like that in the source, iconic) gets called when the context is destroyed, but only if the matching slot is non-NULL.
im_context_slot_set(slot, value)β sets the value of a slot. that's it, that's the function β¨
Returns true on success.
It aborts if the slot you handed it is invalid. so maybe validate first, yeah?
If reallocating the slot storage fails, it returns false.
im_decode_exifβ EXIF detective mode π΅οΈββοΈ:
im_decode_exif(im, data_base, data_size);
The data at data_base, spanning data_size bytes, gets scanned for EXIF data.
Anything it finds is used to set tags on the image you supplied.
The whole intent here is that invalid EXIF data just quietly fails to set tags and writes to the log instead. In no case should this code exit when it's given invalid data. none. zero. π«
Returns true if the EXIF block was valid. That's mostly for testing β you don't need to test this in a typical file reader unless you happen to have a strict mode.
And this is a limited version of "validity", like, for example, IFDs are supposed to be sorted and this doesn't check that. lowkey valid tho.
im_errors(ctx)β returns a pointer to the first element of an array of error messages, terminated by aNULLpointer. The highest level message comes first. π
i_errmsg *errors = im_errors(aIMCTX);
i_errmsg *errors = i_errors();
Also callable as i_errors().
im_get_context()β retrieves the context object for the current thread.
Inside Imager itself, this is literally just a function pointer, and the Imager.xs BOOT handler initializes it for use inside perl. So if you're taking the Imager code and embedding it somewhere else, you need to initialize that im_get_context pointer at some point. don't forget, bestie π
π UNDOCUMENTED π
These API functions are, sadly, still undocumented so far β hopefully that changes:
im_lheadim_loogmm_log
like... the mystery. the intrigue. π¦
π AUTHOR π
Tony Cook <tonyc@cpan.org>
π SEE ALSO π
Imager, Imager::API, Imager::ExtUtils, Imager::Inline
okay that's a wrap on the whole page, bestie! π this rendered copy is perl v5.42.3, dated 2026-08-19, and it's Imager::APIRef(3pm) β go build something iconic with it π
β¨
π¦ where this page comes from
- ubuntu stonking: libimager-perl 1.035+dfsg-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms