在Java中创建图像的缩略图

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在Java中创建图像的缩略图相关的知识,希望对你有一定的参考价值。

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

以上是关于在Java中创建图像的缩略图的主要内容,如果未能解决你的问题,请参考以下文章

如何在 html 中创建具有较低分辨率图像的缩略图

如何在.net core 中创建缩略图?使用 IFormFile 的帮助

在swift中创建网页缩略图

UIImageWriteToSavedPhotosAlbum 在相机胶卷中创建黑色缩略图

在iphone中创建pdf缩略图

如何使用引导程序和 for 循环在 django 中创建电影片段?