如何在上传后以缩略图格式存储jpeg,gif,图像

时间:2010-02-04 13:24:13

标签: java

我通过java api上传图片,gif文件,之后我想以缩略图格式保存文件。

4 个答案:

答案 0 :(得分:1)

来自http://viralpatel.net/blogs/2009/05/20-useful-java-code-snippets-for-java-developers.html

private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)
02          throws InterruptedException, FileNotFoundException, IOException
03      {
04          // load image from filename
05          Image image = Toolkit.getDefaultToolkit().getImage(filename);
06          MediaTracker mediaTracker = new MediaTracker(new Container());
07          mediaTracker.addImage(image, 0);
08          mediaTracker.waitForID(0);
09          // use this to test for errors at this point: System.out.println(mediaTracker.isErrorAny());
10   
11          // determine thumbnail size from WIDTH and HEIGHT
12          double thumbRatio = (double)thumbWidth / (double)thumbHeight;
13          int imageWidth = image.getWidth(null);
14          int imageHeight = image.getHeight(null);
15          double imageRatio = (double)imageWidth / (double)imageHeight;
16          if (thumbRatio < imageRatio) {
17              thumbHeight = (int)(thumbWidth / imageRatio);
18          } else {
19              thumbWidth = (int)(thumbHeight * imageRatio);
20          }
21   
22          // draw original image to thumbnail image object and
23          // scale it to the new size on-the-fly
24          BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
25          Graphics2D graphics2D = thumbImage.createGraphics();
26          graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
27          graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
28   
29          // save thumbnail image to outFilename
30          BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));
31          JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
32          JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
33          quality = Math.max(0, Math.min(quality, 100));
34          param.setQuality((float)quality / 100.0f, false);
35          encoder.setJPEGEncodeParam(param);
36          encoder.encode(thumbImage);
37          out.close();
38      }

你需要弄清楚所有类的来源,但看起来他们没有使用任何未与JDK捆绑的东西(尽管我可能错了)。

答案 1 :(得分:0)

通常没有“缩略图格式”这样的东西,而是使用图像库将上传的图像调整为特定的小尺寸,压缩它们,并与原件一起保存。

我不熟悉Java中的图像格式库,但肯定会有其他人回答这个问题。

答案 2 :(得分:0)

请按照以下步骤操作:

  1. 从上传的商品中获取InputStream
  2. 使用ImageIO加载并重新缩放图片(谷歌搜索“java scale image”)
  3. 将新缩放的图片保存为imagename_thumb.extension

答案 3 :(得分:0)

您可以查看this。这是一个德国团体,但那里提供的代码是英语: - )