Posted By:
Leonid_Trusov
Posted On:
Thursday, September 29, 2005 05:31 PM
I am trying to resize images in the code called from servlet. What I get is 1K images (resolution 100x100) that show as black. I just got into playing with this, so I'm sure there is some simple silly thing. First I tried this piece of code: (width = target width = 100; srcImage holds source image.) BufferedImage bufimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = bufimg.createGraphics(); g.setComposite(AlphaComposite.Src); AffineTransform aft = AffineTransform.getScaleInstance(scalingFactor, scalingFactor); g.drawImage(new ImageIcon(srcImage.getName()).getImage() , aft, null); FileOutputStream os = new FileO
More>>
I am trying to resize images in the code called from servlet. What I get is 1K images (resolution 100x100) that show as black. I just got into playing with this, so I'm sure there is some simple silly thing.
First I tried this piece of code:
(width = target width = 100; srcImage holds source image.)
BufferedImage bufimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufimg.createGraphics();
g.setComposite(AlphaComposite.Src);
AffineTransform aft = AffineTransform.getScaleInstance(scalingFactor, scalingFactor);
g.drawImage(new ImageIcon(srcImage.getName()).getImage() , aft, null);
FileOutputStream os = new FileOutputStream(thumbFile);
if(srcImage.getType().equals("image/jpeg")) {
JPEGImageEncoder enc =
JPEGCodec.createJPEGEncoder(os);
enc.encode(bufimg);
}
os.close();
and then pretty much copied the code(with minor changes) from:
http://java.sun.com/developer/TechTips/1999/tt1021.html
Image inImage = new ImageIcon(srcImage.getName()).getImage();
// Determine the scale.
double scale = (double) width/(double)inImage.getWidth(null);
// Determine size of new image. One of them should equal maxDim.
int scaledW = (int)(scale*inImage.getWidth(null));
int scaledH = (int)(scale*inImage.getHeight(null));
// Create an image buffer in which to paint on.
BufferedImage outImage =
new BufferedImage(scaledW, scaledH, BufferedImage.TYPE_INT_RGB);
// Set the scale.
AffineTransform tx = new AffineTransform();
// If the image is smaller than the desired image size, don't bother scaling.
if (scale
< 1.0d)
{
tx.scale(scale, scale);
}
// Paint image.
Graphics2D g2d = outImage.createGraphics();
g2d.drawImage(inImage, tx, null);
g2d.dispose();
// JPEG-encode the image and write to file.
OutputStream os = new FileOutputStream(thumbFile);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
encoder.encode(outImage);
outImage.flush();
os.close();
Getting the same result. Any hints as to what I am missing ?
Thanks in advance.
<<Less