Crop transparent image

Hello,

I have a method for cropping images. But it only works for non-transparent. If I submit a transparent image using my method, the returned images does not preserve the transparent color.

How can I preserve transparency automatically? Or should I manually set transparency for subimages? How can I do that?


	private static Image[] cropImage(Image pImage, int pCropWidth,
			int pCropHeight) {
		int i = 0;
		int j = 0;
		Vector<Image> imgs = new Vector<Image>();
		boolean finished = false;

		while (!finished) {
			if ((i + pCropWidth) > pImage.getWidth(null)) {
				i = 0;
				j += pCropHeight;
			}

			if ((j + pCropHeight) <= pImage.getHeight(null)) {
				Image image1;
				CropImageFilter cropimagefilter = new CropImageFilter(i, j,
						pCropWidth, pCropHeight);
				FilteredImageSource filteredimagesource = new FilteredImageSource(
						pImage.getSource(), cropimagefilter);
				image1 = Toolkit.getDefaultToolkit().createImage(
						filteredimagesource);
				imgs.add(image1);
				i += pCropWidth;
			} else {
				pImage.flush();
				finished = true;
			}
		}

		Image[] tmp = new Image[imgs.size()];

		for (int e = 0; e < tmp.length; e++) {
			tmp[e] = imgs.get(e);
		}

		return tmp;
	}


Assuming you are using BufferedImages… Why don’t you use getSubImage? It would be easier, take advantage of potential hardware acceleration, and also work with transparency.