-
FEATURED COMPONENTS
First time here? Check out the FAQ!
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; }
Here is the link that I got most of the code from :
Java Forums Image manipulation code
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); bi = ImageIO.read(bais); 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); }
Did you read javadoc ? http://www.potix.com/javadoc/
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
Asked: 2008-09-19 18:45:15 +0800
Seen: 1,040 times
Last updated: Sep 22 '08