ImageUtils.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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) throws IOException {
  12. BufferedImage bufferedImage = ImageIO.read(image);
  13. return Thumbnails.of(bufferedImage)
  14. .size(Math.min(width, bufferedImage.getWidth()), Math.min(height, bufferedImage.getHeight()))
  15. .outputFormat("jpg")
  16. .asBufferedImage();
  17. }
  18. public static BufferedImage resizePng(InputStream image, int width, int height, boolean compress) throws IOException {
  19. BufferedImage bufferedImage = ImageIO.read(image);
  20. BufferedImage img = Thumbnails.of(bufferedImage)
  21. .size(Math.min(width, bufferedImage.getWidth()), Math.min(height, bufferedImage.getHeight()))
  22. .outputFormat("png")
  23. .asBufferedImage();
  24. bufferedImage.flush();
  25. return img;
  26. }
  27. public static BufferedImage resizePng1(InputStream image, int width, int height, boolean compress) throws IOException {
  28. BufferedImage bufferedImage = ImageIO.read(image);
  29. BufferedImage img = Thumbnails.of(bufferedImage)
  30. .size(Math.min(width, bufferedImage.getWidth()), Math.min(height, bufferedImage.getHeight()))
  31. .outputFormat("png")
  32. .asBufferedImage();
  33. bufferedImage.flush();
  34. PngQuant pngQuant = new PngQuant();
  35. return pngQuant.getRemapped(img);
  36. }
  37. public static void main(String[] args) throws IOException {
  38. ImageUtils.resizePng(new FileInputStream("/Users/drew/Downloads/盲盒详情.png"), 1000, 2000, true);
  39. PngQuant pngQuant = new PngQuant();
  40. ImageIO.write(pngQuant
  41. .getRemapped(ImageIO.read(new File("/Users/drew/Desktop/1.png"))),
  42. "png", new File("/Users/drew/Desktop/2.png"));
  43. }
  44. }