| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- package com.izouma.nineth.utils;
- import net.coobird.thumbnailator.Thumbnails;
- import org.pngquant.PngQuant;
- import javax.imageio.ImageIO;
- import java.awt.image.BufferedImage;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- public class ImageUtils {
- public static BufferedImage resizeJpg(InputStream image, int width, int height, boolean compress) throws IOException {
- BufferedImage bufferedImage = ImageIO.read(image);
- return resizeJpg(bufferedImage, width, height, compress);
- }
- public static BufferedImage resizeJpg(BufferedImage bufferedImage, int width, int height, boolean compress) throws IOException {
- return Thumbnails.of(bufferedImage)
- .size(Math.min(width, bufferedImage.getWidth()), Math.min(height, bufferedImage.getHeight()))
- .outputFormat("jpg")
- .outputQuality(compress ? 0.7 : 1.0)
- .asBufferedImage();
- }
- public static BufferedImage resizePng(InputStream image, int width, int height, boolean compress) throws IOException {
- BufferedImage bufferedImage = ImageIO.read(image);
- return resizePng(bufferedImage, width, height, compress);
- }
- public static BufferedImage resizePng(BufferedImage bufferedImage, int width, int height, boolean compress) throws IOException {
- if (compress) {
- BufferedImage img = Thumbnails.of(bufferedImage)
- .size(Math.min(width, bufferedImage.getWidth()), Math.min(height, bufferedImage.getHeight()))
- .outputFormat("png")
- .outputQuality(1.0)
- .asBufferedImage();
- PngQuant pngQuant = new PngQuant();
- return pngQuant.getRemapped(img);
- } else {
- return Thumbnails.of(bufferedImage)
- .size(Math.min(width, bufferedImage.getWidth()), Math.min(height, bufferedImage.getHeight()))
- .outputFormat("png")
- .outputQuality(1.0)
- .asBufferedImage();
- }
- }
- public static void main(String[] args) throws IOException {
- ImageUtils.resizePng(new FileInputStream("/Users/drew/Downloads/盲盒详情.png"), 1000, 2000, true);
- PngQuant pngQuant = new PngQuant();
- ImageIO.write(pngQuant
- .getRemapped(ImageIO.read(new File("/Users/drew/Desktop/1.png"))),
- "png", new File("/Users/drew/Desktop/2.png"));
- }
- }
|