ImageUtils.java 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package com.izouma.nineth.utils;
  2. import net.coobird.thumbnailator.Thumbnails;
  3. import org.pngquant.PngQuant;
  4. import javax.imageio.ImageIO;
  5. import java.awt.image.BufferedImage;
  6. import java.io.File;
  7. import java.io.FileInputStream;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. public class ImageUtils {
  11. public static BufferedImage resizeJpg(InputStream image, int width, int height, boolean compress) throws IOException {
  12. BufferedImage bufferedImage = ImageIO.read(image);
  13. return resizeJpg(bufferedImage, width, height, compress);
  14. }
  15. public static BufferedImage resizeJpg(BufferedImage bufferedImage, int width, int height, boolean compress) throws IOException {
  16. return Thumbnails.of(bufferedImage)
  17. .size(Math.min(width, bufferedImage.getWidth()), Math.min(height, bufferedImage.getHeight()))
  18. .outputFormat("jpg")
  19. .outputQuality(compress ? 0.7 : 1.0)
  20. .asBufferedImage();
  21. }
  22. public static BufferedImage resizePng(InputStream image, int width, int height, boolean compress) throws IOException {
  23. BufferedImage bufferedImage = ImageIO.read(image);
  24. return resizePng(bufferedImage, width, height, compress);
  25. }
  26. public static BufferedImage resizePng(BufferedImage bufferedImage, int width, int height, boolean compress) throws IOException {
  27. if (compress) {
  28. BufferedImage img = Thumbnails.of(bufferedImage)
  29. .size(Math.min(width, bufferedImage.getWidth()), Math.min(height, bufferedImage.getHeight()))
  30. .outputFormat("png")
  31. .outputQuality(1.0)
  32. .asBufferedImage();
  33. PngQuant pngQuant = new PngQuant();
  34. return pngQuant.getRemapped(img);
  35. } else {
  36. return Thumbnails.of(bufferedImage)
  37. .size(Math.min(width, bufferedImage.getWidth()), Math.min(height, bufferedImage.getHeight()))
  38. .outputFormat("png")
  39. .outputQuality(1.0)
  40. .asBufferedImage();
  41. }
  42. }
  43. public static void main(String[] args) throws IOException {
  44. ImageUtils.resizePng(new FileInputStream("/Users/drew/Downloads/盲盒详情.png"), 1000, 2000, true);
  45. PngQuant pngQuant = new PngQuant();
  46. ImageIO.write(pngQuant
  47. .getRemapped(ImageIO.read(new File("/Users/drew/Desktop/1.png"))),
  48. "png", new File("/Users/drew/Desktop/2.png"));
  49. }
  50. }