# Scaling Images

ansancle
317 9

This post isn't necessarily entirely about ZK, but does anyone have any sample code of taking a byte[] that represents an image and then being able to scale it into a ZK image of a different size?
For example, a 128px wide and 128px high image is read from the db, I want to scale it down to 32x32.

I know how to create a java.awt.Image, BufferedImage, and then a ZK Image and have tried several things from examples on the web, just doesn't work. I get a black box of the correct size but no image.

Here is what I had tried :

	public org.zkoss.zul.Image scaleImage(byte[] imageBlob,int width,int height)
{
ImageObserver observer = null;
java.awt.Image image = Toolkit.getDefaultToolkit().createImage(imageBlob);
java.awt.Image scaledImage = image.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH);
BufferedImage bufferedImage = new BufferedImage ( width,
height,
BufferedImage.SCALE_SMOOTH  );
Graphics2D graphics = bufferedImage.createGraphics();
graphics.drawImage( scaledImage, 0, 0, observer);

org.zkoss.zul.Image zkImage = new org.zkoss.zul.Image();
zkImage.setContent(bufferedImage);
return zkImage;
}


delete retag edit

## 3 Replies

dennis
3669 1 6
http://www.javaworld.com....

I don't think zkImage.setContent can accept BufferedIamge, the argument must be a org.zkoss.image.Image .
try to warp the byte[] of bufferedImage with AImage object , and use AImage as argument of Image.setContent

/Dennis

ansancle
317 9

I found the solution to scaling images, the following sample code handles the task. Of course this could be rewritten into one clean method but I was just testing different things and happen to get it to work and wanted to post it up here.
Enjoy.

	 public BufferedImage getImage(byte[] data) throws Exception
{
BufferedImage bi = null;
ByteArrayInputStream bais = new ByteArrayInputStream(data);
return bi;
}

public org.zkoss.zul.Image scaleImage(byte[] imageBlob,int width,int height) throws Exception
{
java.awt.image.BufferedImage scaledImage = getImage(imageBlob);
scaledImage = scaleToSize(width,height,scaledImage);
Image zkImage = new Image();
zkImage.setContent(scaledImage);
return zkImage;
}

public BufferedImage scaleToSize(int nMaxWidth, int nMaxHeight, BufferedImage imgSrc)
{
int nHeight = imgSrc.getHeight();
int nWidth = imgSrc.getWidth();
double scaleX = (double)nMaxWidth / (double)nWidth;
double scaleY = (double)nMaxHeight / (double)nHeight;
double fScale = Math.min(scaleX, scaleY);
return scale(fScale, imgSrc);
}



ansancle
317 9

Here is the link that I got most of the code from :
Java Forums Image manipulation code

[hide preview]