Java 2D Resize

Posted by jon077 on Stack Overflow See other posts from Stack Overflow or by jon077
Published on 2009-02-12T20:39:10Z Indexed on 2010/05/13 10:24 UTC
Read the original article Hit count: 328

Filed under:
|
|
|

I have some old Java 2D code I want to reuse, but was wondering, is this the best way to get the highest quality images?

    public static BufferedImage getScaled(BufferedImage imgSrc, Dimension dim) {

	//	This code ensures that all the pixels in the image are loaded.
	Image scaled = imgSrc.getScaledInstance(
			dim.width, dim.height, Image.SCALE_SMOOTH);

	// This code ensures that all the pixels in the image are loaded.
	Image temp = new ImageIcon(scaled).getImage();

	// Create the buffered image.
	BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), 
			temp.getHeight(null), BufferedImage.TYPE_INT_RGB);

	// Copy image to buffered image.
	Graphics g = bufferedImage.createGraphics();
	// Clear background and paint the image.
	g.setColor(Color.white);
	g.fillRect(0, 0, temp.getWidth(null),temp.getHeight(null));
	g.drawImage(temp, 0, 0, null);
	g.dispose();


	// j2d's image scaling quality is rather poor, especially when
	// scaling down an image to a much smaller size. We'll post filter  
	// our images using a trick found at 
	// http://blogs.cocoondev.org/mpo/archives/003584.html
	// to increase the perceived quality....
	float origArea = imgSrc.getWidth() * imgSrc.getHeight();
	float newArea = dim.width * dim.height;
	if (newArea <= (origArea / 2.)) {
		bufferedImage = blurImg(bufferedImage);
	}

	return bufferedImage;
}

public static BufferedImage blurImg(BufferedImage src) {
	// soften factor - increase to increase blur strength
	float softenFactor = 0.010f;
	// convolution kernel (blur)
	float[] softenArray = {
			0, 				softenFactor, 		0, 
			softenFactor, 1-(softenFactor*4), softenFactor, 
			0, 				softenFactor, 		0};

	Kernel kernel = new Kernel(3, 3, softenArray);
	ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
	return cOp.filter(src, null);
}

© Stack Overflow or respective owner

Related posts about java

Related posts about 2d