Class PImage
- All Implemented Interfaces:
Cloneable
,PConstants
Before using the pixels[] array, be sure to use the loadPixels() method on the image to make sure that the pixel data is properly loaded.
To create a new image, use the createImage() function. Do not use the syntax new PImage().
- See Also:
- Usage:
- Web & Application
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final int
static final int
int
Format for this image, one of RGB, ARGB or ALPHA.static final int
int
The height of the image in units of pixels.boolean
Loaded pixels flagPath to parent object that will be used with save().int
1 for most images, 2 for hi-dpi/retinaint
int[]
The pixels[] array contains the values for all the pixels in the image.int
Actual dimensions of pixels array, taking into account the 2x setting.static final int
int
The width of the image in units of pixels.Fields inherited from interface processing.core.PConstants
ADD, ALPHA, ALT, AMBIENT, ARC, ARGB, ARROW, BACKSPACE, BASELINE, BEVEL, BEZIER_VERTEX, BLEND, BLUR, BOTTOM, BOX, BREAK, BURN, CENTER, CHATTER, CHORD, CLAMP, CLOSE, CODED, COMPLAINT, CONTROL, CORNER, CORNERS, CROSS, CURVE_VERTEX, CUSTOM, DARKEST, DEG_TO_RAD, DELETE, DIAMETER, DIFFERENCE, DILATE, DIRECTIONAL, DISABLE_ASYNC_SAVEFRAME, DISABLE_BUFFER_READING, DISABLE_DEPTH_MASK, DISABLE_DEPTH_SORT, DISABLE_DEPTH_TEST, DISABLE_KEY_REPEAT, DISABLE_NATIVE_FONTS, DISABLE_OPENGL_ERRORS, DISABLE_OPTIMIZED_STROKE, DISABLE_STROKE_PERSPECTIVE, DISABLE_STROKE_PURE, DISABLE_TEXTURE_MIPMAPS, DODGE, DOWN, DXF, ELLIPSE, ENABLE_ASYNC_SAVEFRAME, ENABLE_BUFFER_READING, ENABLE_DEPTH_MASK, ENABLE_DEPTH_SORT, ENABLE_DEPTH_TEST, ENABLE_KEY_REPEAT, ENABLE_NATIVE_FONTS, ENABLE_OPENGL_ERRORS, ENABLE_OPTIMIZED_STROKE, ENABLE_STROKE_PERSPECTIVE, ENABLE_STROKE_PURE, ENABLE_TEXTURE_MIPMAPS, ENTER, EPSILON, ERODE, ESC, EXCLUSION, FX2D, GIF, GRAY, GROUP, HALF_PI, HAND, HARD_LIGHT, HINT_COUNT, HSB, IMAGE, INVERT, JAVA2D, JPEG, LANDSCAPE, LEFT, LIGHTEST, LINE, LINE_LOOP, LINE_STRIP, LINES, LINUX, MACOS, MACOSX, MAX_FLOAT, MAX_INT, MIN_FLOAT, MIN_INT, MITER, MODEL, MODELVIEW, MOVE, MULTIPLY, NORMAL, OPAQUE, OPEN, OPENGL, ORTHOGRAPHIC, OTHER, OVERLAY, P2D, P3D, PATH, PDF, PERSPECTIVE, PI, PIE, platformNames, POINT, POINTS, POLYGON, PORTRAIT, POSTERIZE, PROBLEM, PROJECT, PROJECTION, QUAD, QUAD_BEZIER_VERTEX, QUAD_STRIP, QUADRATIC_VERTEX, QUADS, QUARTER_PI, RAD_TO_DEG, RADIUS, RECT, REPEAT, REPLACE, RETURN, RGB, RIGHT, ROUND, SCREEN, SHAPE, SHIFT, SOFT_LIGHT, SPAN, SPHERE, SPOT, SQUARE, SUBTRACT, SVG, TAB, TARGA, TAU, TEXT, THIRD_PI, THRESHOLD, TIFF, TOP, TRIANGLE, TRIANGLE_FAN, TRIANGLE_STRIP, TRIANGLES, TWO_PI, UP, VERTEX, WAIT, WHITESPACE, WINDOWS, X, Y, Z
-
Constructor Summary
ConstructorsConstructorDescriptionPImage()
( begin auto-generated from PImage.xml ) Datatype for storing images.PImage
(int width, int height) PImage
(int width, int height, int format) PImage
(int width, int height, int[] pixels, boolean requiresCheckAlpha, PApplet parent, int format, int factor) PImage
(int width, int height, int format, int factor) Deprecated. -
Method Summary
Modifier and TypeMethodDescriptionvoid
blend
(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) void
Blends a region of pixels into the image specified by the img parameter.static int
blendColor
(int c1, int c2, int mode) Blends two color values together based on the blending mode given as the MODE parameter.void
Check the alpha on an image, using a really primitive loop.clone()
Duplicate an image, returns new PImage object.copy()
void
copy
(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) Copies a region of pixels from one image into another.void
void
filter
(int kind) void
filter
(int kind, float param) Filters the image as defined by one of the following modes:
THRESHOLD
Converts the image to black and white pixels depending on if they are above or below the threshold defined by the level parameter.get()
Returns a copy of this PImage.int
get
(int x, int y) Reads the color of any pixel or grabs a section of an image.get
(int x, int y, int w, int h) getImage()
Deprecated.int
int
int
int
void
init
(int width, int height, int format) Do not remove, see notes in the other variant.void
init
(int width, int height, int format, int factor) Function to be used by subclasses of PImage to init later than at the constructor, or re-init later when things change.boolean
isLoaded()
boolean
void
Loads the pixel data of the current display window into the pixels[] array.static PImage
loadTGA
(InputStream input) Targa image loader for RLE-compressed TGA files.void
mask
(int[] maskArray) void
Masks part of an image from displaying by loading another image and using it as an alpha channel.void
resize
(int w, int h) Resize the image to a new width and height.boolean
Saves the image into a file.void
set
(int x, int y, int c) Changes the color of any pixel or writes an image directly into the display window.
The x and y parameters specify the pixel to change and the color parameter specifies the color value.void
Advancedvoid
void
setLoaded
(boolean l) void
void
setModified
(boolean m) void
void
updatePixels
(int x, int y, int w, int h) Updates the display window with the data in the pixels[] array.
-
Field Details
-
format
public int formatFormat for this image, one of RGB, ARGB or ALPHA. note that RGB images still require 0xff in the high byte because of how they'll be manipulated by other functions -
pixels
public int[] pixelsThe pixels[] array contains the values for all the pixels in the image. These values are of the color datatype. This array is the size of the image, meaning if the image is 100 x 100 pixels, there will be 10,000 values and if the window is 200 x 300 pixels, there will be 60,000 values.
Before accessing this array, the data must be loaded with the loadPixels() method. Failure to do so may result in a NullPointerException. After the array data has been modified, the updatePixels() method must be run to update the content of the display window.- Usage:
- web_application
-
pixelDensity
public int pixelDensity1 for most images, 2 for hi-dpi/retina -
pixelWidth
public int pixelWidthActual dimensions of pixels array, taking into account the 2x setting. -
pixelHeight
public int pixelHeight -
width
public int widthThe width of the image in units of pixels.- Usage:
- web_application
-
height
public int heightThe height of the image in units of pixels.- Usage:
- web_application
-
parent
Path to parent object that will be used with save(). This prevents users from needing savePath() to use PImage.save(). -
loaded
public boolean loadedLoaded pixels flag -
ALPHA_MASK
public static final int ALPHA_MASK- See Also:
-
RED_MASK
public static final int RED_MASK- See Also:
-
GREEN_MASK
public static final int GREEN_MASK- See Also:
-
BLUE_MASK
public static final int BLUE_MASK- See Also:
-
-
Constructor Details
-
PImage
public PImage()( begin auto-generated from PImage.xml ) Datatype for storing images. Processing can display .gif, .jpg, .tga, and .png images. Images may be displayed in 2D and 3D space. Before an image is used, it must be loaded with the loadImage() function. The PImage object contains fields for the width and height of the image, as well as an array called pixels[] which contains the values for every pixel in the image. A group of methods, described below, allow easy access to the image's pixels and alpha channel and simplify the process of compositing.
Before using the pixels[] array, be sure to use the loadPixels() method on the image to make sure that the pixel data is properly loaded.
To create a new image, use the createImage() function (do not use new PImage()).- See Also:
- Usage:
- web_application
-
PImage
public PImage(int width, int height) - Parameters:
width
- image widthheight
- image height
-
PImage
public PImage(int width, int height, int format) - Parameters:
format
- Either RGB, ARGB, ALPHA (grayscale alpha channel)
-
PImage
public PImage(int width, int height, int format, int factor) -
PImage
-
PImage
public PImage(int width, int height, int[] pixels, boolean requiresCheckAlpha, PApplet parent, int format, int factor) -
PImage
Deprecated.
-
-
Method Details
-
init
public void init(int width, int height, int format) Do not remove, see notes in the other variant. -
init
public void init(int width, int height, int format, int factor) Function to be used by subclasses of PImage to init later than at the constructor, or re-init later when things change. Used by Capture and Movie classes (and perhaps others), because the width/height will not be known when super() is called. (Leave this public so that other libraries can do the same.) -
checkAlpha
public void checkAlpha()Check the alpha on an image, using a really primitive loop. -
getImage
Deprecated.Use the getNative() method instead, which allows library interfaces to be written in a cross-platform fashion for desktop, Android, and others. This is still included for PGraphics objects, which may need the image. -
getNative
-
isModified
public boolean isModified() -
setModified
public void setModified() -
setModified
public void setModified(boolean m) -
getModifiedX1
public int getModifiedX1() -
getModifiedX2
public int getModifiedX2() -
getModifiedY1
public int getModifiedY1() -
getModifiedY2
public int getModifiedY2() -
loadPixels
public void loadPixels()Loads the pixel data of the current display window into the pixels[] array. This function must always be called before reading from or writing to pixels[]. Subsequent changes to the display window will not be reflected in pixels until loadPixels() is called again.Advanced
Call this when you want to mess with the pixels[] array. For subclasses where the pixels[] buffer isn't set by default, this should copy all data into the pixels[] array- Usage:
- web_application
-
updatePixels
public void updatePixels() -
updatePixels
public void updatePixels(int x, int y, int w, int h) Updates the display window with the data in the pixels[] array. Use in conjunction with loadPixels(). If you're only reading pixels from the array, there's no need to call updatePixels() — updating is only necessary to apply changes.Advanced
Mark the pixels in this region as needing an update. This is not currently used by any of the renderers, however the api is structured this way in the hope of being able to use this to speed things up in the future.- Parameters:
x
- x-coordinate of the upper-left cornery
- y-coordinate of the upper-left cornerw
- widthh
- height- Usage:
- web_application
-
clone
Duplicate an image, returns new PImage object. The pixels[] array for the new object will be unique and recopied from the source image. This is implemented as an override of Object.clone(). We recommend using get() instead, because it prevents you from needing to catch the CloneNotSupportedException, and from doing a cast from the result.- Throws:
CloneNotSupportedException
-
resize
public void resize(int w, int h) Resize the image to a new width and height. To make the image scale proportionally, use 0 as the value for the wide or high parameter. For instance, to make the width of an image 150 pixels, and change the height using the same proportion, use resize(150, 0).
Even though a PGraphics is technically a PImage, it is not possible to rescale the image data found in a PGraphics. (It's simply not possible to do this consistently across renderers: technically infeasible with P3D, or what would it even do with PDF?) If you want to resize PGraphics content, first get a copy of its image data using the get() method, and call resize() on the PImage that is returned.- Parameters:
w
- the resized image widthh
- the resized image height- See Also:
- Usage:
- web_application
-
isLoaded
public boolean isLoaded() -
setLoaded
public void setLoaded() -
setLoaded
public void setLoaded(boolean l) -
get
public int get(int x, int y) Reads the color of any pixel or grabs a section of an image. If no parameters are specified, the entire image is returned. Use the x and y parameters to get the value of one pixel. Get a section of the display window by specifying an additional width and height parameter. When getting an image, the x and y parameters define the coordinates for the upper-left corner of the image, regardless of the current imageMode().
If the pixel requested is outside the image window, black is returned. The numbers returned are scaled according to the current color ranges, but only RGB values are returned by this function. For example, even though you may have drawn a shape with colorMode(HSB), the numbers returned will be in RGB format.
Getting the color of a single pixel with get(x, y) is easy, but not as fast as grabbing the data directly from pixels[]. The equivalent statement to get(x, y) using pixels[] is pixels[y*width+x]. See the reference for pixels[] for more information.Advanced
Returns an ARGB "color" type (a packed 32-bit int) with the color. If the coordinate is outside the image, zero is returned (black, but completely transparent).If the image is in RGB format (i.e. on a PVideo object), the value will get its high bits set, just to avoid cases where they haven't been set already.
If the image is in ALPHA format, this returns a white with its alpha value set.
This function is included primarily for beginners. It is quite slow because it has to check to see if the x, y that was provided is inside the bounds, and then has to check to see what image type it is. If you want things to be more efficient, access the pixels[] array directly.
- Parameters:
x
- x-coordinate of the pixely
- y-coordinate of the pixel- See Also:
- Usage:
- web_application
-
get
- Parameters:
w
- width of pixel rectangle to geth
- height of pixel rectangle to get
-
get
Returns a copy of this PImage. Equivalent to get(0, 0, width, height). Deprecated, just use copy() instead. -
copy
-
set
public void set(int x, int y, int c) Changes the color of any pixel or writes an image directly into the display window.
The x and y parameters specify the pixel to change and the color parameter specifies the color value. The color parameter is affected by the current color mode (the default is RGB values from 0 to 255). When setting an image, the x and y parameters define the coordinates for the upper-left corner of the image, regardless of the current imageMode().
Setting the color of a single pixel with set(x, y) is easy, but not as fast as putting the data directly into pixels[]. The equivalent statement to set(x, y, #000000) using pixels[] is pixels[y*width+x] = #000000. See the reference for pixels[] for more information.- Parameters:
x
- x-coordinate of the pixely
- y-coordinate of the pixelc
- any value of the color datatype- See Also:
- Usage:
- web_application
-
set
Advanced
Efficient method of drawing an image's pixels directly to this surface. No variations are employed, meaning that any scale, tint, or imageMode settings will be ignored.- Parameters:
img
- image to copy into the original image
-
mask
public void mask(int[] maskArray) - Parameters:
maskArray
- array of integers used as the alpha channel, needs to be the same length as the image's pixel array.
-
mask
Masks part of an image from displaying by loading another image and using it as an alpha channel. This mask image should only contain grayscale data, but only the blue color channel is used. The mask image needs to be the same size as the image to which it is applied.
In addition to using a mask image, an integer array containing the alpha channel data can be specified directly. This method is useful for creating dynamically generated alpha masks. This array must be of the same length as the target image's pixels array and should contain only grayscale data of values between 0-255.Advanced
Set alpha channel for an image. Black colors in the source image will make the destination image completely transparent, and white will make things fully opaque. Gray values will be in-between steps.Strictly speaking the "blue" value from the source image is used as the alpha color. For a fully grayscale image, this is correct, but for a color image it's not 100% accurate. For a more accurate conversion, first use filter(GRAY) which will make the image into a "correct" grayscale by performing a proper luminance-based conversion.
- Parameters:
img
- image to use as the mask- Usage:
- web_application
-
filter
public void filter(int kind) -
filter
public void filter(int kind, float param) Filters the image as defined by one of the following modes:
THRESHOLD
Converts the image to black and white pixels depending on if they are above or below the threshold defined by the level parameter. The parameter must be between 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used.
GRAY
Converts any colors in the image to grayscale equivalents. No parameter is used.
OPAQUE
Sets the alpha channel to entirely opaque. No parameter is used.
INVERT
Sets each pixel to its inverse value. No parameter is used.
POSTERIZE
Limits each channel of the image to the number of colors specified as the parameter. The parameter can be set to values between 2 and 255, but results are most noticeable in the lower ranges.
BLUR
Executes a Gaussian blur with the level parameter specifying the extent of the blurring. If no parameter is used, the blur is equivalent to Gaussian blur of radius 1. Larger values increase the blur.
ERODE
Reduces the light areas. No parameter is used.
DILATE
Increases the light areas. No parameter is used.Advanced
Method to apply a variety of basic filters to this image.- filter(BLUR) provides a basic blur.
- filter(GRAY) converts the image to grayscale based on luminance.
- filter(INVERT) will invert the color components in the image.
- filter(OPAQUE) set all the high bits in the image to opaque
- filter(THRESHOLD) converts the image to black and white.
- filter(DILATE) grow white/light areas
- filter(ERODE) shrink white/light areas
- Parameters:
kind
- Either THRESHOLD, GRAY, OPAQUE, INVERT, POSTERIZE, BLUR, ERODE, or DILATEparam
- unique for each, see above- Usage:
- web_application
-
copy
public void copy(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) Copies a region of pixels from one image into another. If the source and destination regions aren't the same size, it will automatically resize source pixels to fit the specified target region. No alpha information is used in the process, however if the source image has an alpha channel set, it will be copied as well.
As of release 0149, this function ignores imageMode().- Parameters:
sx
- X coordinate of the source's upper left cornersy
- Y coordinate of the source's upper left cornersw
- source image widthsh
- source image heightdx
- X coordinate of the destination's upper left cornerdy
- Y coordinate of the destination's upper left cornerdw
- destination image widthdh
- destination image height- See Also:
- Usage:
- web_application
-
copy
- Parameters:
src
- an image variable referring to the source image.
-
blendColor
public static int blendColor(int c1, int c2, int mode) Blends two color values together based on the blending mode given as the MODE parameter. The possible modes are described in the reference for the blend() function.Advanced
- REPLACE - destination colour equals colour of source pixel: C = A. Sometimes called "Normal" or "Copy" in other software.
- BLEND - linear interpolation of colours: C = A*factor + B
- ADD - additive blending with white clip: C = min(A*factor + B, 255). Clipped to 0..255, Photoshop calls this "Linear Burn", and Director calls it "Add Pin".
- SUBTRACT - subtractive blend with black clip: C = max(B - A*factor, 0). Clipped to 0..255, Photoshop calls this "Linear Dodge", and Director calls it "Subtract Pin".
- DARKEST - only the darkest colour succeeds: C = min(A*factor, B). Illustrator calls this "Darken".
- LIGHTEST - only the lightest colour succeeds: C = max(A*factor, B). Illustrator calls this "Lighten".
- DIFFERENCE - subtract colors from underlying image.
- EXCLUSION - similar to DIFFERENCE, but less extreme.
- MULTIPLY - Multiply the colors, result will always be darker.
- SCREEN - Opposite multiply, uses inverse values of the colors.
- OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, and screens light values.
- HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower.
- SOFT_LIGHT - Mix of DARKEST and LIGHTEST. Works like OVERLAY, but not as harsh.
- DODGE - Lightens light tones and increases contrast, ignores darks. Called "Color Dodge" in Illustrator and Photoshop.
- BURN - Darker areas are applied, increasing contrast, ignores lights. Called "Color Burn" in Illustrator and Photoshop.
A useful reference for blending modes and their algorithms can be found in the SVG specification.
It is important to note that Processing uses "fast" code, not necessarily "correct" code. No biggie, most software does. A nitpicker can find numerous "off by 1 division" problems in the blend code where >>8 or >>7 is used when strictly speaking /255.0 or /127.0 should have been used.
For instance, exclusion (not intended for real-time use) reads r1 + r2 - ((2 * r1 * r2) / 255) because 255 == 1.0 not 256 == 1.0. In other words, (255*255)>>8 is not the same as (255*255)/255. But for real-time use the shifts are preferable, and the difference is insignificant for applications built with Processing.
- Parameters:
c1
- the first color to blendc2
- the second color to blendmode
- either BLEND, ADD, SUBTRACT, DARKEST, LIGHTEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, or BURN- See Also:
- Usage:
- web_application
-
blend
public void blend(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) -
blend
public void blend(PImage src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) Blends a region of pixels into the image specified by the img parameter. These copies utilize full alpha channel support and a choice of the following modes to blend the colors of source pixels (A) with the ones of pixels in the destination image (B):
BLEND - linear interpolation of colours: C = A*factor + B
ADD - additive blending with white clip: C = min(A*factor + B, 255)
SUBTRACT - subtractive blending with black clip: C = max(B - A*factor, 0)
DARKEST - only the darkest colour succeeds: C = min(A*factor, B)
LIGHTEST - only the lightest colour succeeds: C = max(A*factor, B)
DIFFERENCE - subtract colors from underlying image.
EXCLUSION - similar to DIFFERENCE, but less extreme.
MULTIPLY - Multiply the colors, result will always be darker.
SCREEN - Opposite multiply, uses inverse values of the colors.
OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, and screens light values.
HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower.
SOFT_LIGHT - Mix of DARKEST and LIGHTEST. Works like OVERLAY, but not as harsh.
DODGE - Lightens light tones and increases contrast, ignores darks. Called "Color Dodge" in Illustrator and Photoshop.
BURN - Darker areas are applied, increasing contrast, ignores lights. Called "Color Burn" in Illustrator and Photoshop.
All modes use the alpha information (the highest byte) of source image pixels as the blending factor. If the source and destination regions are different sizes, the image will be automatically resized to match the destination size. If the srcImg parameter is not used, the display window is used as the source image.
As of release 0149, this function ignores imageMode().- Parameters:
src
- an image variable referring to the source imagesx
- X coordinate of the source's upper left cornersy
- Y coordinate of the source's upper left cornersw
- source image widthsh
- source image heightdx
- X coordinate of the destination's upper left cornerdy
- Y coordinate of the destination's upper left cornerdw
- destination image widthdh
- destination image heightmode
- Either BLEND, ADD, SUBTRACT, LIGHTEST, DARKEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN- See Also:
-
loadTGA
Targa image loader for RLE-compressed TGA files.Rewritten for 0115 to read/write RLE-encoded targa images. For 0125, non-RLE encoded images are now supported, along with images whose y-order is reversed (which is standard for TGA files).
A version of this function is in MovieMaker.java. Any fixes here should be applied over in MovieMaker as well.
Known issue with RLE encoding and odd behavior in some apps: https://github.com/processing/processing/issues/2096 Please help!
- Throws:
IOException
-
save
Saves the image into a file. Append a file extension to the name of the file, to indicate the file format to be used: either TIFF (.tif), TARGA (.tga), JPEG (.jpg), or PNG (.png). If no extension is included in the filename, the image will save in TIFF format and .tif will be added to the name. These files are saved to the sketch's folder, which may be opened by selecting "Show sketch folder" from the "Sketch" menu.
To save an image created within the code, rather than through loading, it's necessary to make the image with the createImage() function, so it is aware of the location of the program and can therefore save the file to the right place. See the createImage() reference for more information.Advanced
Save this image to disk.As of revision 0100, this function requires an absolute path, in order to avoid confusion. To save inside the sketch folder, use the function savePath() from PApplet, or use saveFrame() instead. As of revision 0116, savePath() is not needed if this object has been created (as recommended) via createImage() or createGraphics() or one of its neighbors.
As of revision 0115, when using Java 1.4 and later, you can write to several formats besides tga and tiff. If Java 1.4 is installed and the extension used is supported (usually png, jpg, jpeg, bmp, and tiff), then those methods will be used to write the image. To get a list of the supported formats for writing, use:
println(javax.imageio.ImageIO.getReaderFormatNames())In Processing 4.0 beta 5, the old (and sometimes buggy) TIFF reader/writer was removed, so ImageIO is used for TIFF files.
Also, files must have an extension: we're no longer adding .tif to files with no extension, because that can lead to confusing results, and the behavior is inconsistent with the rest of the API.
- Parameters:
filename
- a sequence of letters and numbers- Usage:
- application
-