Java Code Examples for java.awt.image.PixelGrabber#grabPixels()

The following examples show how to use java.awt.image.PixelGrabber#grabPixels() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
private static int[] makeGradientPallet() {
  BufferedImage image = new BufferedImage(100, 1, BufferedImage.TYPE_INT_RGB);
  Graphics2D g2 = image.createGraphics();
  Point2D start = new Point2D.Float();
  Point2D end = new Point2D.Float(99f, 0f);
  float[] dist = {0f, .5f, 1f};
  Color[] colors = {Color.RED, Color.YELLOW, Color.GREEN};
  g2.setPaint(new LinearGradientPaint(start, end, dist, colors));
  g2.fillRect(0, 0, 100, 1);
  g2.dispose();

  int width = image.getWidth(null);
  int[] pallet = new int[width];
  PixelGrabber pg = new PixelGrabber(image, 0, 0, width, 1, pallet, 0, width);
  try {
    pg.grabPixels();
  } catch (InterruptedException ex) {
    ex.printStackTrace();
    Toolkit.getDefaultToolkit().beep();
    Thread.currentThread().interrupt();
  }
  return pallet;
}
 
Example 2
Source File: ImageUtils.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
/**
    * Cretae a BufferedImage from an ImageProducer.
    * @param producer the ImageProducer
    * @return a new TYPE_INT_ARGB BufferedImage
    */
   public static BufferedImage createImage(ImageProducer producer) {
	PixelGrabber pg = new PixelGrabber(producer, 0, 0, -1, -1, null, 0, 0);
	try {
		pg.grabPixels();
	} catch (InterruptedException e) {
		throw new RuntimeException("Image fetch interrupted");
	}
	if ((pg.status() & ImageObserver.ABORT) != 0)
		throw new RuntimeException("Image fetch aborted");
	if ((pg.status() & ImageObserver.ERROR) != 0)
		throw new RuntimeException("Image fetch error");
	BufferedImage p = new BufferedImage(pg.getWidth(), pg.getHeight(), BufferedImage.TYPE_INT_ARGB);
	p.setRGB(0, 0, pg.getWidth(), pg.getHeight(), (int[])pg.getPixels(), 0, pg.getWidth());
	return p;
}
 
Example 3
Source File: UIUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static Color getGTKProfilerResultsBackground() {
    int[] pixels = new int[1];
    pixels[0] = -1;
    
    // Prepare textarea to grab the color from
    JTextArea textArea = new JTextArea();
    textArea.setSize(new Dimension(10, 10));
    textArea.doLayout();
    
    // Print the textarea to an image
    Image image = new BufferedImage(textArea.getSize().width, textArea.getSize().height, BufferedImage.TYPE_INT_RGB);
    textArea.printAll(image.getGraphics());
    
    // Grab appropriate pixels to get the color
    PixelGrabber pixelGrabber = new PixelGrabber(image, 5, 5, 1, 1, pixels, 0, 1);
    try {
        pixelGrabber.grabPixels();
        if (pixels[0] == -1) return Color.WHITE; // System background not customized
    } catch (InterruptedException e) {
        return getNonGTKProfilerResultsBackground();
    }
    
    return pixels[0] != -1 ? new Color(pixels[0]) : getNonGTKProfilerResultsBackground();
}
 
Example 4
Source File: ImageUtil.java    From nextreports-designer with Apache License 2.0 6 votes vote down vote up
private static boolean hasAlpha(Image image) {
    // If buffered image, the color model is readily available
    if (image instanceof BufferedImage) {
        BufferedImage bimage = (BufferedImage) image;
        return bimage.getColorModel().hasAlpha();
    }

    // Use a pixel grabber to retrieve the image's color model;
    // grabbing a single pixel is usually sufficient
    PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
    try {
        pg.grabPixels();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // Get the image's color model
    ColorModel cm = pg.getColorModel();
    return cm.hasAlpha();
}
 
Example 5
Source File: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
public static int[] makeGradientPallet() {
  BufferedImage image = new BufferedImage(100, 1, BufferedImage.TYPE_INT_RGB);
  Graphics2D g2 = image.createGraphics();
  Point2D start = new Point2D.Float();
  Point2D end = new Point2D.Float(99f, 0f);
  float[] dist = {.0f, .5f, 1f};
  Color[] colors = {Color.RED, Color.YELLOW, Color.GREEN};
  g2.setPaint(new LinearGradientPaint(start, end, dist, colors));
  g2.fillRect(0, 0, 100, 1);
  g2.dispose();

  int width = image.getWidth(null);
  int[] pallet = new int[width];
  PixelGrabber pg = new PixelGrabber(image, 0, 0, width, 1, pallet, 0, width);
  try {
    pg.grabPixels();
  } catch (InterruptedException ex) {
    ex.printStackTrace();
    Toolkit.getDefaultToolkit().beep();
    Thread.currentThread().interrupt();
  }
  return pallet;
}
 
Example 6
Source File: PostscriptWriter.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
private ArrayImageSource getImageSource( Image image ) throws IOException
{
	ImageIcon imageIcon = new ImageIcon( image );
	int w = imageIcon.getIconWidth( );
	int h = imageIcon.getIconHeight( );
	int[] pixels = new int[w * h];

	try
	{
		PixelGrabber pg = new PixelGrabber( image, 0, 0, w, h, pixels, 0, w );
		pg.grabPixels( );
		if ( ( pg.getStatus( ) & ImageObserver.ABORT ) != 0 )
		{
			throw new IOException( "failed to load image contents" );
		}
	}
	catch ( InterruptedException e )
	{
		throw new IOException( "image load interrupted" );
	}

	ArrayImageSource imageSource = new ArrayImageSource( w, h, pixels );
	return imageSource;
}
 
Example 7
Source File: UIUtils.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
private static Color getGTKProfilerResultsBackground() {
    int[] pixels = new int[1];
    pixels[0] = -1;
    
    // Prepare textarea to grab the color from
    JTextArea textArea = new JTextArea();
    textArea.setSize(new Dimension(10, 10));
    textArea.doLayout();
    
    // Print the textarea to an image
    Image image = new BufferedImage(textArea.getSize().width, textArea.getSize().height, BufferedImage.TYPE_INT_RGB);
    textArea.printAll(image.getGraphics());
    
    // Grab appropriate pixels to get the color
    PixelGrabber pixelGrabber = new PixelGrabber(image, 5, 5, 1, 1, pixels, 0, 1);
    try {
        pixelGrabber.grabPixels();
        if (pixels[0] == -1) return Color.WHITE; // System background not customized
    } catch (InterruptedException e) {
        return getNonGTKProfilerResultsBackground();
    }
    
    return pixels[0] != -1 ? new Color(pixels[0]) : getNonGTKProfilerResultsBackground();
}
 
Example 8
Source File: Patch.java    From TrakEM2 with GNU General Public License v3.0 6 votes vote down vote up
/** Expects x,y in world coordinates.  This method is intended for grabing an occasional pixel; to grab all pixels, see @getImageProcessor method. */
public int[] getPixel(final int x, final int y, final double mag) {
	if (project.getLoader().isUnloadable(this)) return new int[4];
	final MipMapImage mipMap = project.getLoader().fetchImage(this, mag);
	if (Loader.isSignalImage(mipMap.image)) return new int[4];
	final int w = mipMap.image.getWidth(null);
	final Point2D.Double pd = inverseTransformPoint(x, y);
	final int x2 = (int)(pd.x / mipMap.scaleX);
	final int y2 = (int)(pd.y / mipMap.scaleY);
	final int[] pvalue = new int[4];
	final PixelGrabber pg = new PixelGrabber( mipMap.image, x2, y2, 1, 1, pvalue, 0, w);
	try {
		pg.grabPixels();
	} catch (final InterruptedException ie) {
		return pvalue;
	}

	approximateTransferPixel(pvalue);

	return pvalue;
}
 
Example 9
Source File: GraphicsUtils.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
/**
 * 分割指定图像为image[]
 * 
 * @param image
 * @param row
 * @param col
 * @return
 */
public static Image[][] getSplit2Images(Image image, int row, int col, boolean isFiltrate) {
	int wlength = image.getWidth(null) / row;
	int hlength = image.getHeight(null) / col;
	Image[][] abufferedimage = new Image[wlength][hlength];
	for (int y = 0; y < hlength; y++) {
		for (int x = 0; x < wlength; x++) {
			abufferedimage[x][y] = GraphicsUtils.createImage(row, col, true);
			Graphics g = abufferedimage[x][y].getGraphics();
			g.drawImage(image, 0, 0, row, col, (x * row), (y * col), row + (x * row), col + (y * col), null);
			g.dispose();
			g = null;
			PixelGrabber pgr = new PixelGrabber(abufferedimage[x][y], 0, 0, -1, -1, true);
			try {
				pgr.grabPixels();
			} catch (InterruptedException ex) {
				ex.getStackTrace();
			}
			int pixels[] = (int[]) pgr.getPixels();
			if (isFiltrate) {
				for (int i = 0; i < pixels.length; i++) {
					int[] rgbs = LColor.getRGBs(pixels[i]);
					if ((rgbs[0] == 247 && rgbs[1] == 0 && rgbs[2] == 255)
							|| (rgbs[0] == 255 && rgbs[1] == 0 && rgbs[2] == 255)
							|| (rgbs[0] == 0 && rgbs[1] == 0 && rgbs[2] == 0)) {
						pixels[i] = 0;
					}
				}
			}
			ImageProducer ip = new MemoryImageSource(pgr.getWidth(), pgr.getHeight(), pixels, 0, pgr.getWidth());
			abufferedimage[x][y] = toolKit.createImage(ip);
		}
	}
	return abufferedimage;
}
 
Example 10
Source File: FSLoader.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
/** Returns the array of pixels, whose type depends on the bi.getType(); for example, for a BufferedImage.TYPE_BYTE_INDEXED, returns a byte[]. */
static public final Object grabPixels(final BufferedImage bi) {
	final PixelGrabber pg = new PixelGrabber(bi, 0, 0, bi.getWidth(), bi.getHeight(), false);
	try {
		pg.grabPixels();
		return pg.getPixels();
	} catch (InterruptedException e) {
		IJError.print(e);
	}
	return null;
}
 
Example 11
Source File: ImageUtil.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Converts the buffered image into a sprite image and returns it
 * @param image  The image to be converted
 * @param client Current client instance
 * @return       The buffered image as a sprite image
 */
public static SpritePixels getImageSpritePixels(BufferedImage image, Client client)
{
	int[] pixels = new int[image.getWidth() * image.getHeight()];

	try
	{
		PixelGrabber g = new PixelGrabber(image, 0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth());
		g.setColorModel(new DirectColorModel(32, 0xff0000, 0xff00, 0xff, 0xff000000));
		g.grabPixels();

		// Make any fully transparent pixels fully black, because the sprite draw routines
		// check for == 0, not actual transparency
		for (int i = 0; i < pixels.length; i++)
		{
			if ((pixels[i] & 0xFF000000) == 0)
			{
				pixels[i] = 0;
			}
		}
	}
	catch (InterruptedException ex)
	{
		log.debug("PixelGrabber was interrupted: ", ex);
	}

	return client.createSpritePixels(pixels, image.getWidth(), image.getHeight());
}
 
Example 12
Source File: ImageWrapper.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
private void writeObject ( ObjectOutputStream stream ) throws java.io.IOException {
   stream.defaultWriteObject( ); // write non-transient, non-static data
   PixelGrabber grabber = new PixelGrabber( image , 0 , 0 , -1 , -1 , true );
   
   try {
      grabber.grabPixels( );
   } catch ( InterruptedException e ) {}
   Object pix = grabber.getPixels( );
   Dimension dim = new Dimension( image.getWidth( null ) , image.getHeight( null ) );
   stream.writeObject( dim );
   stream.writeObject( pix );
}
 
Example 13
Source File: ImageFilter.java    From JewelCrawler with GNU General Public License v3.0 5 votes vote down vote up
/** 线性灰度变换 */
public BufferedImage lineGrey() {
	PixelGrabber pg = new PixelGrabber(image.getSource(), 0, 0, iw, ih, pixels, 0, iw);
	try {
		pg.grabPixels();
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	// 对图像进行进行线性拉伸,Alpha值保持不变
	ColorModel cm = ColorModel.getRGBdefault();
	for (int i = 0; i < iw * ih; i++) {
		int alpha = cm.getAlpha(pixels[i]);
		int red = cm.getRed(pixels[i]);
		int green = cm.getGreen(pixels[i]);
		int blue = cm.getBlue(pixels[i]);

		// 增加了图像的亮度
		red = (int) (1.1 * red + 30);
		green = (int) (1.1 * green + 30);
		blue = (int) (1.1 * blue + 30);
		if (red >= 255) {
			red = 255;
		}
		if (green >= 255) {
			green = 255;
		}
		if (blue >= 255) {
			blue = 255;
		}
		pixels[i] = alpha << 24 | red << 16 | green << 8 | blue;
	}

	// 将数组中的象素产生一个图像

	return ImageIOHelper.imageProducerToBufferedImage(new MemoryImageSource(iw, ih, pixels, 0, iw));
}
 
Example 14
Source File: ExportARGB.java    From TrakEM2 with GNU General Public License v3.0 5 votes vote down vote up
static public final int[] extractARGBIntArray( final Image img )
{
	final int[] pix = new int[img.getWidth(null) * img.getHeight(null)];
	PixelGrabber pg = new PixelGrabber( img, 0, 0, img.getWidth(null), img.getHeight(null), pix, 0, img.getWidth(null) );
	try {
		pg.grabPixels();
	} catch (InterruptedException ie) {}
	return pix;
}
 
Example 15
Source File: ImageUtils.java    From jivejdon with Apache License 2.0 5 votes vote down vote up
/**
 * Determines if the image has transparent pixels.
 * 
 * @param image The image to check for transparent pixel.s
 * @return <code>true</code> of <code>false</code>, according to the result
 */
public static boolean hasAlpha(Image image){
	try {
		PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
		pg.grabPixels();

		return pg.getColorModel().hasAlpha();
	}
	catch (InterruptedException e) {
		return false;
	}
}
 
Example 16
Source File: WMFGraphics.java    From openchemlib-js with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public int setGDIFillBrush()
{
    int i = brushhandle;

    if (brushfillstyle == 3) {
        if (brushpattern != null) {
            int j = brushpattern.getWidth(null);
            int k = brushpattern.getHeight(null);
            int[] ai = new int[j * k];
            PixelGrabber pixelgrabber = new PixelGrabber(brushpattern, 0, 0, j, k, ai, 0, j);

            try {
                pixelgrabber.grabPixels();

                if ((pixelgrabber.status() & 0x80) != 0) {
                    brushhandle = wmf.createBrushIndirect(0, foreground, brushhatch);
                } else {
                    brushhandle = wmf.createPatternBrush(ai, j, k);
                }
            } catch (InterruptedException _ex) {
                brushhandle = wmf.createBrushIndirect(0, foreground, brushhatch);
            }
        } else {
            brushhandle = wmf.createBrushIndirect(0, foreground, brushhatch);
        }
    } else {
        brushhandle = wmf.createBrushIndirect(brushfillstyle, foreground, brushhatch);
    }

    wmf.selectObject(brushhandle);
    wmf.deleteObject(i);
    state.setBrush(brushhandle);

    return brushhandle;
}
 
Example 17
Source File: BarCode.java    From util with Apache License 2.0 4 votes vote down vote up
protected Image zlkj(Image image, int i, int j, int k)
{
    int l = image.getWidth(null);
    int i1 = image.getHeight(null);
    if(j > l)
        j = l;
    if(k > i1)
        k = i1;
    int ai[] = new int[l * i1];
    int ai1[] = new int[j * k];
    PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, l, i1, ai, 0, l);
    try
    {
        pixelgrabber.grabPixels();
    }
    catch(InterruptedException interruptedexception)
    {
        System.err.println("interrupted waiting for pixels!");
        return null;
    }
    if((pixelgrabber.getStatus() & 0x80) != 0)
    {
        System.err.println("image fetch aborted or errored");
        return null;
    }
    if(i == 90)
    {
        for(int j1 = 0; j1 < j; j1++)
        {
            for(int i2 = 0; i2 < k; i2++)
                ai1[k * (j - (j1 + 1)) + i2] = ai[i2 * l + j1];

        }

        return Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(k, j, ai1, 0, k));
    }
    if(i == 180)
    {
        for(int k1 = 0; k1 < j; k1++)
        {
            for(int j2 = 0; j2 < k; j2++)
                ai1[(k - (j2 + 1)) * j + (j - (k1 + 1))] = ai[j2 * l + k1];

        }

        return Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(j, k, ai1, 0, j));
    }
    if(i == 270)
    {
        for(int l1 = 0; l1 < j; l1++)
        {
            for(int k2 = 0; k2 < k; k2++)
                ai1[k * l1 + (k - (k2 + 1))] = ai[k2 * l + l1];

        }

        return Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(k, j, ai1, 0, k));
    } else
    {
        return null;
    }
}
 
Example 18
Source File: AnimationHelper.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
public static AnimationHelper makeObject(String fileName, int tileWidth, int tileHeight, Color col) {
	String key = fileName.trim().toLowerCase();
	AnimationHelper animation = (AnimationHelper) animations.get(key);
	if (animation == null) {
		Image image = GraphicsUtils.loadNotCacheImage(fileName);
		int c = col.getRGB();
		int wlength = image.getWidth(null) / tileWidth;
		int hlength = image.getHeight(null) / tileHeight;
		Image[][] images = new Image[wlength][hlength];
		for (int y = 0; y < hlength; y++) {
			for (int x = 0; x < wlength; x++) {
				images[x][y] = GraphicsUtils.createImage(tileWidth, tileHeight, true);
				Graphics g = images[x][y].getGraphics();
				g.drawImage(image, 0, 0, tileWidth, tileHeight, (x * tileWidth), (y * tileHeight),
						tileWidth + (x * tileWidth), tileHeight + (y * tileHeight), null);
				g.dispose();
				g = null;
				PixelGrabber pgr = new PixelGrabber(images[x][y], 0, 0, -1, -1, true);
				try {
					pgr.grabPixels();
				} catch (InterruptedException ex) {
					ex.getStackTrace();
				}
				int pixels[] = (int[]) pgr.getPixels();
				for (int i = 0; i < pixels.length; i++) {
					if (pixels[i] == c) {
						pixels[i] = 0;
					}
				}
				ImageProducer ip = new MemoryImageSource(pgr.getWidth(), pgr.getHeight(), pixels, 0,
						pgr.getWidth());
				images[x][y] = GraphicsUtils.toolKit.createImage(ip);
			}
		}
		Image[][] result = new Image[hlength][wlength];
		for (int y = 0; y < wlength; y++) {
			for (int x = 0; x < hlength; x++) {
				result[x][y] = images[y][x];
			}
		}
		images = null;
		animations.put(key, animation = makeObject(result[0], result[1], result[3], result[2]));
	}
	return animation;

}
 
Example 19
Source File: ExportBestFlatImage.java    From TrakEM2 with GNU General Public License v3.0 4 votes vote down vote up
/**
 *
    * @return null when the dimensions make the array larger than 2GB, or the image otherwise.
   */
public ByteProcessor makeFlatGrayImage()
{
	if ( canUseAWTImage() ) {
		final Image img = createAWTImage( ImagePlus.GRAY8 );
		try {
		// Try fastest way: direct way of grabbing the underlying pixel array
			if (img instanceof BufferedImage && BufferedImage.TYPE_BYTE_GRAY == ((BufferedImage)img).getType()) {
				return new ByteProcessor( (BufferedImage)img );
			}
			final PixelGrabber pg = new PixelGrabber(img, 0, 0, img.getWidth(null), img.getHeight(null), false);
			try {
				pg.grabPixels();
			} catch (final InterruptedException ie) {
				ie.printStackTrace();
			}
			if (pg.getColorModel() instanceof IndexColorModel) {
				return new ByteProcessor(img.getWidth(null), img.getHeight(null), (byte[])pg.getPixels(), null);
			} else {
				// Let's be creative
				return new ColorProcessor(img).convertToByteProcessor();
			}
		} finally {
			img.flush();
		}
	}

	if ( !isSmallerThan2GB() ) {
		Utils.log("Cannot create an image larger than 2 GB.");
		return null;
	}

	if ( loader.isMipMapsRegenerationEnabled() )
	{
		// Use mipmaps directly: they are already Gaussian-downsampled
		// (TODO waste: generates an alpha mask that is then not used)
		return ExportUnsignedByte.makeFlatImageFromMipMaps( patches, finalBox, 0, scale ).a;
	}

	// Else: no mipmaps
	return ExportUnsignedByte.makeFlatImageFromOriginals( patches, finalBox, 0, scale ).a;
}
 
Example 20
Source File: MyImage.java    From Java-Image-Processing-Project with MIT License 3 votes vote down vote up
/**
 * Initialize the pixel array
 * Image origin is at coordinate (0,0)
 * (0,0)--------> X-axis
 *     |
 *     |
 *     |
 *     v
 *   Y-axis
 * 
 * This method will store the value of each pixels of a 2D image in a 1D array.
 */
private void initPixelArray(){
    PixelGrabber pg = new PixelGrabber(image, 0, 0, width, height, pixels, 0, width);
    try{
        pg.grabPixels();
    }catch(InterruptedException e){
        System.out.println("Error Occurred: "+e);
    }
}