PDA

View Full Version : thumbnail


BubikolRamios
07-17-2009, 01:04 PM
ok, lost here. This works as expected, but instead of thumbnail of actual, just uploaded image creates thumbnail of randome or something image that is in the same dir where original img was before upload.
Sometime it works as it should.

imgFilePath and thumbPath are like:
uploadFolder/nameOfImageFile


//http://javaxden.blogspot.com/2007/08/creatin-thumbnail.html
// res returns actual width and height in px
public static int createThumbnail( StringBuffer res,
String imgFilePath,
String thumbPath,
int thumbWidth,// max
int thumbHeight// min
)throws Exception
{



Image image = Toolkit.getDefaultToolkit().getImage(imgFilePath);
MediaTracker mediaTracker = new MediaTracker(new Container());
mediaTracker.addImage(image, 0);
mediaTracker.waitForID(0);
double thumbRatio = (double)thumbWidth / (double)thumbHeight;
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
double imageRatio = (double)imageWidth / (double)imageHeight;
if (thumbRatio < imageRatio)
{
thumbHeight = (int)(thumbWidth / imageRatio);
}
else
{
thumbWidth = (int)(thumbHeight * imageRatio);
}
BufferedImage thumbImage = new BufferedImage(thumbWidth,
thumbHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = thumbImage.createGraphics();
// nalsednjo vrstico lahko zakomentiram ce ne rabim HQ image
//in lahko dam RenderingHints.VALUE_INTERPOLATION_BICUBIC ker v nekaterih primerih da bolji rezultat
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILI NEAR);
graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
BufferedOutputStream out = new BufferedOutputStream(new
FileOutputStream(thumbPath));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.
getDefaultJPEGEncodeParam(thumbImage);
int quality = 100;
param.setQuality((float)quality / 100.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(thumbImage);
out.close();

res.append(thumbWidth);
res.append("|" + thumbHeight);
return 0;

}