如何用Java中的JPEG创建缩略图? [英] How do you create a thumbnail image out of a JPEG in Java?
问题描述
有人可以帮助我们帮助创建一些用Java创建JPEG缩略图的代码。
Can someone please help with some code for creating a thumbnail for a JPEG in Java.
我是新手,所以一步一步的解释是赞。
I'm new at this, so a step by step explanation would be appreciated.
推荐答案
Image img = ImageIO.read(new File("test.jpg")).getScaledInstance(100, 100, BufferedImage.SCALE_SMOOTH);
这将创建一个100x100像素的缩略图作为Image对象。如果你想把它写回磁盘,只需将代码转换为:
This will create a 100x100 pixels thumbnail as an Image object. If you want to write it back to disk simply convert the code to this:
BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
img.createGraphics().drawImage(ImageIO.read(new File("test.jpg")).getScaledInstance(100, 100, Image.SCALE_SMOOTH),0,0,null);
ImageIO.write(img, "jpg", new File("test_thumb.jpg"));
此外,如果您担心速度问题(如果您想扩展,上述方法相当慢许多图片)使用这些方法和以下声明:
Also if you are concerned about speed issues (the method described above is rather slow if you want to scale many images) use these methods and the following declaration :
private BufferedImage scale(BufferedImage source,double ratio) {
int w = (int) (source.getWidth() * ratio);
int h = (int) (source.getHeight() * ratio);
BufferedImage bi = getCompatibleImage(w, h);
Graphics2D g2d = bi.createGraphics();
double xScale = (double) w / source.getWidth();
double yScale = (double) h / source.getHeight();
AffineTransform at = AffineTransform.getScaleInstance(xScale,yScale);
g2d.drawRenderedImage(source, at);
g2d.dispose();
return bi;
}
private BufferedImage getCompatibleImage(int w, int h) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage image = gc.createCompatibleImage(w, h);
return image;
}
然后致电:
BufferedImage scaled = scale(img,0.5);
其中0.5是比例,img是包含正常大小图像的BufferedImage。
where 0.5 is the scale ratio and img is a BufferedImage containing the normal-sized image.
这篇关于如何用Java中的JPEG创建缩略图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!