Class PImage

  • All Implemented Interfaces:
    Cloneable, PConstants
    Direct Known Subclasses:
    PGraphics

    public class PImage
    extends Object
    implements PConstants, Cloneable
    ( 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 class contains fields for the width and height of the image, as well as an array called pixels[] that contains the values for every pixel in the image. The methods described below allow easy access to the image's pixels and alpha channel and simplify the process of compositing.

    using the pixels[] array, be sure to use the loadPixels() method on the image to make sure that the pixel data is properly loaded.

    create a new image, use the createImage() function. Do not use the syntax new PImage(). ( end auto-generated )
    See Also:
    PApplet.loadImage(String), PApplet.imageMode(int), PApplet.createImage(int, int, int)
    • Field Detail

      • format

        public int format
        Format 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[] pixels
        ( begin auto-generated from pixels.xml ) Array containing the values for all the pixels in the display window. These values are of the color datatype. This array is the size of the display window. For example, if the image is 100x100 pixels, there will be 10000 values and if the window is 200x300 pixels, there will be 60000 values. The index value defines the position of a value within the array. For example, the statement color b = pixels[230] will set the variable b to be equal to the value at that location in the array.

        Before accessing this array, the data must loaded with the loadPixels() function. After the array data has been modified, the updatePixels() function must be run to update the changes. Without loadPixels(), running the code may (or will in future releases) result in a NullPointerException. ( end auto-generated )
      • pixelDensity

        public int pixelDensity
        1 for most images, 2 for hi-dpi/retina
      • pixelWidth

        public int pixelWidth
        Actual dimensions of pixels array, taking into account the 2x setting.
      • pixelHeight

        public int pixelHeight
      • width

        public int width
        ( begin auto-generated from PImage_width.xml ) The width of the image in units of pixels. ( end auto-generated )
      • height

        public int height
        ( begin auto-generated from PImage_height.xml ) The height of the image in units of pixels. ( end auto-generated )
      • parent

        public PApplet parent
        Path to parent object that will be used with save(). This prevents users from needing savePath() to use PImage.save().
      • modified

        protected boolean modified
        modified portion of the image
      • mx1

        protected int mx1
      • my1

        protected int my1
      • mx2

        protected int mx2
      • my2

        protected int my2
      • loaded

        public boolean loaded
        Loaded pixels flag
      • saveImageFormats

        protected String[] saveImageFormats
    • Constructor Detail

      • 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()). ( end auto-generated )
        See Also:
        PApplet.loadImage(String, String), PApplet.imageMode(int), PApplet.createImage(int, int, int)
      • PImage

        public PImage​(int width,
                      int height)
        Parameters:
        width - image width
        height - 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

        public PImage​(Image img)
        Construct a new PImage from a java.awt.Image. This constructor assumes that you've done the work of making sure a MediaTracker has been used to fully download the data and that the img is valid.
        Parameters:
        img - assumes a MediaTracker has been used to fully download the data and the img is valid
    • Method Detail

      • 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 changes. 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

        protected void checkAlpha()
        Check the alpha on an image, using a really primitive loop.
      • getImage

        public Image getImage()
        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

        public Object getNative()
        Returns a native BufferedImage from this PImage.
      • 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()
        ( begin auto-generated from PImage_loadPixels.xml ) Loads the pixel data for the image into its pixels[] array. This function must always be called before reading from or writing to pixels[].

        renderers may or may not seem to require loadPixels() or updatePixels(). However, the rule is that any time you want to manipulate the pixels[] array, you must first call loadPixels(), and after changes have been made, call updatePixels(). Even if the renderer may not seem to use this function in the current Processing release, this will always be subject to change. ( end auto-generated )

        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

      • updatePixels

        public void updatePixels()
      • updatePixels

        public void updatePixels​(int x,
                                 int y,
                                 int w,
                                 int h)
        ( begin auto-generated from PImage_updatePixels.xml ) Updates the image with the data in its pixels[] array. Use in conjunction with loadPixels(). If you're only reading pixels from the array, there's no need to call updatePixels().

        renderers may or may not seem to require loadPixels() or updatePixels(). However, the rule is that any time you want to manipulate the pixels[] array, you must first call loadPixels(), and after changes have been made, call updatePixels(). Even if the renderer may not seem to use this function in the current Processing release, this will always be subject to change.

        Currently, none of the renderers use the additional parameters to updatePixels(), however this may be implemented in the future. ( end auto-generated )

        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 corner
        y - y-coordinate of the upper-left corner
        w - width
        h - height
      • clone

        public Object clone()
                     throws CloneNotSupportedException
        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.
        Overrides:
        clone in class Object
        Throws:
        CloneNotSupportedException
      • resize

        public void resize​(int w,
                           int h)
        ( begin auto-generated from PImage_resize.xml ) 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. ( end auto-generated )
        Parameters:
        w - the resized image width
        h - the resized image height
        See Also:
        get(int, int, int, int)
      • isLoaded

        public boolean isLoaded()
      • setLoaded

        public void setLoaded()
      • setLoaded

        public void setLoaded​(boolean l)
      • get

        public int get​(int x,
                       int y)
        ( begin auto-generated from PImage_get.xml ) 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 of 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. ( end auto-generated )

        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 pixel
        y - y-coordinate of the pixel
        See Also:
        PApplet.set(int, int, int), PApplet.pixels, PApplet.copy(PImage, int, int, int, int, int, int, int, int)
      • get

        public PImage get​(int x,
                          int y,
                          int w,
                          int h)
        Parameters:
        w - width of pixel rectangle to get
        h - height of pixel rectangle to get
      • get

        public PImage get()
        Returns a copy of this PImage. Equivalent to get(0, 0, width, height). Deprecated, just use copy() instead.
      • getImpl

        protected void getImpl​(int sourceX,
                               int sourceY,
                               int sourceWidth,
                               int sourceHeight,
                               PImage target,
                               int targetX,
                               int targetY)
        Internal function to actually handle getting a block of pixels that has already been properly cropped to a valid region. That is, x/y/w/h are guaranteed to be inside the image space, so the implementation can use the fastest possible pixel copying method.
      • set

        public void set​(int x,
                        int y,
                        int c)
        ( begin auto-generated from PImage_set.xml ) 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. ( end auto-generated )
        Parameters:
        x - x-coordinate of the pixel
        y - y-coordinate of the pixel
        c - any value of the color datatype
        See Also:
        get(int, int, int, int), pixels, copy(PImage, int, int, int, int, int, int, int, int)
      • set

        public void set​(int x,
                        int y,
                        PImage img)

        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
      • setImpl

        protected void setImpl​(PImage sourceImage,
                               int sourceX,
                               int sourceY,
                               int sourceWidth,
                               int sourceHeight,
                               int targetX,
                               int targetY)
        Internal function to actually handle setting a block of pixels that has already been properly cropped from the image to a valid region.
      • 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

        public void mask​(PImage img)
        ( begin auto-generated from PImage_mask.xml ) 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. ( end auto-generated )

        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
      • filter

        public void filter​(int kind)
      • filter

        public void filter​(int kind,
                           float param)
        ( begin auto-generated from PImage_filter.xml ) Filters an image as defined by one of the following modes:

        THRESHOLD - converts the image to black and white pixels depending if they are above or below the threshold defined by the level parameter. The level 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

        INVERT - sets each pixel to its inverse value

        POSTERIZE - limits each channel of the image to the number of colors specified as the level parameter

        BLUR - executes a Guassian blur with the level parameter specifying the extent of the blurring. If no level parameter is used, the blur is equivalent to Guassian blur of radius 1

        OPAQUE - sets the alpha channel to entirely opaque

        ERODE - reduces the light areas with the amount defined by the level parameter

        DILATE - increases the light areas with the amount defined by the level parameter ( end auto-generated )

        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
        Luminance conversion code contributed by toxi

        Gaussian blur code contributed by Mario Klingemann

        Parameters:
        kind - Either THRESHOLD, GRAY, OPAQUE, INVERT, POSTERIZE, BLUR, ERODE, or DILATE
        param - unique for each, see above
      • opaque

        protected void opaque()
        Set the high bits of all pixels to opaque.
      • buildBlurKernel

        protected void buildBlurKernel​(float r)
        Optimized code for building the blur kernel. further optimized blur code (approx. 15% for radius=20) bigger speed gains for larger radii (~30%) added support for various image types (ALPHA, RGB, ARGB) [toxi 050728]
      • blurAlpha

        protected void blurAlpha​(float r)
      • blurRGB

        protected void blurRGB​(float r)
      • blurARGB

        protected void blurARGB​(float r)
      • dilate

        protected void dilate()
        Generic dilate/erode filter using luminance values as decision factor. [toxi 050728]
      • erode

        protected void erode()
      • copy

        public void copy​(int sx,
                         int sy,
                         int sw,
                         int sh,
                         int dx,
                         int dy,
                         int dw,
                         int dh)
        ( begin auto-generated from PImage_copy.xml ) 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(). ( end auto-generated )
        Parameters:
        sx - X coordinate of the source's upper left corner
        sy - Y coordinate of the source's upper left corner
        sw - source image width
        sh - source image height
        dx - X coordinate of the destination's upper left corner
        dy - Y coordinate of the destination's upper left corner
        dw - destination image width
        dh - destination image height
        See Also:
        PGraphics.alpha(int), blend(PImage, int, int, int, int, int, int, int, int, int)
      • copy

        public void copy​(PImage src,
                         int sx,
                         int sy,
                         int sw,
                         int sh,
                         int dx,
                         int dy,
                         int dw,
                         int dh)
        Parameters:
        src - an image variable referring to the source image.
      • blendColor

        public static int blendColor​(int c1,
                                     int c2,
                                     int mode)
        ( begin auto-generated from blendColor.xml ) 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. ( end auto-generated )

        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 - substractive 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 preferrable, and the difference is insignificant for applications built with Processing.

        Parameters:
        c1 - the first color to blend
        c2 - the second color to blend
        mode - either BLEND, ADD, SUBTRACT, DARKEST, LIGHTEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, or BURN
        See Also:
        blend(PImage, int, int, int, int, int, int, int, int, int), PApplet.color(float, float, float, float)
      • 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)
        ( begin auto-generated from PImage_blend.xml ) 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 (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(). ( end auto-generated )
        Parameters:
        src - an image variable referring to the source image
        sx - X coordinate of the source's upper left corner
        sy - Y coordinate of the source's upper left corner
        sw - source image width
        sh - source image height
        dx - X coordinate of the destinations's upper left corner
        dy - Y coordinate of the destinations's upper left corner
        dw - destination image width
        dh - destination image height
        mode - Either BLEND, ADD, SUBTRACT, LIGHTEST, DARKEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN
        See Also:
        PApplet.alpha(int), copy(PImage, int, int, int, int, int, int, int, int), blendColor(int,int,int)
      • loadTIFF

        protected static PImage loadTIFF​(byte[] tiff)
      • saveTIFF

        protected boolean saveTIFF​(OutputStream output)
      • saveTGA

        protected boolean saveTGA​(OutputStream output)
        Creates a Targa32 formatted byte sequence of specified pixel buffer using RLE compression.

        Also figured out how to avoid parsing the image upside-down (there's a header flag to set the image origin to top-left)

        Starting with revision 0092, the format setting is taken into account:
        • ALPHA images written as 8bit grayscale (uses lowest byte)
        • RGB → 24 bits
        • ARGB → 32 bits
        All versions are RLE compressed.

        Contributed by toxi 8-10 May 2005, based on this RLE specification
      • saveImageIO

        protected boolean saveImageIO​(String path)
                               throws IOException
        Use ImageIO functions from Java 1.4 and later to handle image save. Various formats are supported, typically jpeg, png, bmp, and wbmp. To get a list of the supported formats for writing, use:
        println(javax.imageio.ImageIO.getReaderFormatNames())
        Throws:
        IOException
      • save

        public boolean save​(String filename)
        ( begin auto-generated from PImage_save.xml ) 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. ( end auto-generated )

        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())

        To use the original built-in image writers, use .tga or .tif as the extension, or don't include an extension. When no extension is used, the extension .tif will be added to the file name.

        The ImageIO API claims to support wbmp files, however they probably require a black and white image. Basic testing produced a zero-length file with no error.

        Parameters:
        filename - a sequence of letters and numbers