Java examples for 2D Graphics:Image
Calculates the bounds of the non-transparent parts of the given image.
//package com.java2s; import java.awt.*; import java.awt.image.*; public class Main { /**/*from w w w . j av a 2s. c o m*/ * Calculates the bounds of the non-transparent parts of the given image. * @param p the image * @return the bounds of the non-transparent area */ public static Rectangle getSelectedBounds(BufferedImage p) { int width = p.getWidth(); int height = p.getHeight(); int maxX = 0, maxY = 0, minX = width, minY = height; boolean anySelected = false; int y1; int[] pixels = null; for (y1 = height - 1; y1 >= 0; y1--) { pixels = getRGB(p, 0, y1, width, 1, pixels); for (int x = 0; x < minX; x++) { if ((pixels[x] & 0xff000000) != 0) { minX = x; maxY = y1; anySelected = true; break; } } for (int x = width - 1; x >= maxX; x--) { if ((pixels[x] & 0xff000000) != 0) { maxX = x; maxY = y1; anySelected = true; break; } } if (anySelected) break; } pixels = null; for (int y = 0; y < y1; y++) { pixels = getRGB(p, 0, y, width, 1, pixels); for (int x = 0; x < minX; x++) { if ((pixels[x] & 0xff000000) != 0) { minX = x; if (y < minY) minY = y; anySelected = true; break; } } for (int x = width - 1; x >= maxX; x--) { if ((pixels[x] & 0xff000000) != 0) { maxX = x; if (y < minY) minY = y; anySelected = true; break; } } } if (anySelected) return new Rectangle(minX, minY, maxX - minX + 1, maxY - minY + 1); return null; } /** * A convenience method for getting ARGB pixels from an image. This tries to avoid the performance * penalty of BufferedImage.getRGB unmanaging the image. * @param image a BufferedImage object * @param x the left edge of the pixel block * @param y the right edge of the pixel block * @param width the width of the pixel arry * @param height the height of the pixel arry * @param pixels the array to hold the returned pixels. May be null. * @return the pixels * @see #setRGB */ public static int[] getRGB(BufferedImage image, int x, int y, int width, int height, int[] pixels) { int type = image.getType(); if (type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_RGB) return (int[]) image.getRaster().getDataElements(x, y, width, height, pixels); return image.getRGB(x, y, width, height, pixels, 0, width); } }