生成缩略图~java

﹏ヽ暗。殇╰゛Y 2024-02-05 20:02 175阅读 0赞

话不多说直接上代码:

  1. public class ImageUtil {
  2. /**
  3. * 生成缩略图
  4. * @param input 资源文件
  5. * @param outputPath 生成缩略图文件夹路径
  6. * @param shrink 缩放比例
  7. * @throws IOException
  8. */
  9. public static File shrinkPic(File input, String outputPath, double shrink) throws IOException {
  10. String name = input.getName();
  11. // 读取原始图像文件
  12. // 创建BufferedImage对象来存储原始图像数据
  13. BufferedImage originalImage = ImageIO.read(input);
  14. // 设置新的图像大小(这里将图像缩小为原来的1/2)
  15. int scaledWidth = (int) (originalImage.getWidth() * shrink);
  16. int scaledHeight = (int) (originalImage.getHeight() * shrink);
  17. // 创建目标图像对象并指定新的大小
  18. BufferedImage resizedImage = new BufferedImage(scaledWidth, scaledHeight, originalImage.getType());
  19. // 获得Graphics2D对象以进行操作
  20. Graphics graphics = resizedImage.getGraphics();
  21. // 调用drawImage()方法进行缩放处理
  22. graphics.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
  23. // 释放Graphics2D对象
  24. graphics.dispose();
  25. // 输出结果到文件或显示在界面上等等...
  26. File output = new File(outputPath + File.separator + name);
  27. ImageIO.write(resizedImage, "jpg", output);
  28. return output;
  29. }
  30. /**
  31. * 生成缩略图
  32. * @param input 资源文件输入流
  33. * @param outputPath 生成缩略图文件夹路径
  34. * @param shrink 缩放比例
  35. * @throws IOException
  36. */
  37. public static File shrinkPic(InputStream input, String outputPath, double shrink) throws IOException {
  38. // 读取原始图像文件
  39. // 创建BufferedImage对象来存储原始图像数据
  40. BufferedImage originalImage = ImageIO.read(input);
  41. // 设置新的图像大小(这里将图像缩小为原来的1/2)
  42. int scaledWidth = (int) (originalImage.getWidth() * shrink);
  43. int scaledHeight = (int) (originalImage.getHeight() * shrink);
  44. // 创建目标图像对象并指定新的大小
  45. BufferedImage resizedImage = new BufferedImage(scaledWidth, scaledHeight, originalImage.getType());
  46. // 获得Graphics2D对象以进行操作
  47. Graphics graphics = resizedImage.getGraphics();
  48. // 调用drawImage()方法进行缩放处理
  49. graphics.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
  50. // 释放Graphics2D对象
  51. graphics.dispose();
  52. // 输出结果到文件或显示在界面上等等...
  53. File output = new File(outputPath);
  54. if (!output.getParentFile().getParentFile().exists()) {
  55. output.getParentFile().mkdirs();
  56. }
  57. if (!output.getParentFile().exists()) {
  58. output.mkdirs();
  59. }
  60. ImageIO.write(resizedImage, "jpg", output);
  61. return output;
  62. }
  63. }

上面两个方法都是返回缩略后的图片文件,不同的是一个传的文件File,一个传的是文件流。

发表评论

表情:
评论列表 (有 0 条评论,175人围观)

还没有评论,来说两句吧...

相关阅读