gpt4 book ai didi

java - 我怎样才能使这个图像缩放器快速?

转载 作者:太空宇宙 更新时间:2023-11-04 08:22:25 24 4
gpt4 key购买 nike

这是我当前拥有的 ImageResizer 类。

目前每个图像大约需要 0.4 秒,当您必须处理 100k 图像时,这非常慢。

请告诉我如何使用 java 使其更快。(请原谅非常肮脏的代码,我已经把它打乱了很多次,但从来没有机会清理它)

package helpers;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class ImageResizer {
public static final int VERTICAL = 0;
public static final int HORIZONTAL = 1;

public static final String IMAGE_JPEG = "jpeg";
public static final String IMAGE_JPG = "jpg";
public static final String IMAGE_PNG = "png";

public static InputStream resizeImage(byte[] image, int maxWidth) {

InputStream inputStream = null;

Image img = (new ImageIcon(image)).getImage();
ImageIcon picture = scaleImage(img, maxWidth, HORIZONTAL);

ByteArrayOutputStream out = new ByteArrayOutputStream();
saveToStream(picture, out, IMAGE_JPEG);

inputStream = new ByteArrayInputStream(out.toByteArray());

return inputStream;
}

public static InputStream getThumbnail(byte[] image) {
return resizeImage(image, 100);
}

private static ImageIcon scaleImage(Image image, int size, int dir) {
if (dir == HORIZONTAL) {
return new ImageIcon(image.getScaledInstance(size, -1, Image.SCALE_FAST));
} else {
return new ImageIcon(image.getScaledInstance(-1, size, Image.SCALE_FAST));
}
}

private static void saveToStream(ImageIcon picture, OutputStream file, String imageType) {
if (picture != null) {
BufferedImage bi = new BufferedImage(picture.getIconWidth(), picture.getIconHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.drawImage(picture.getImage(), 0, 0, null);
try {
ImageIO.write(bi, imageType, file);
} catch (IOException ioe) {
ioe.printStackTrace();
}
} else {
System.out.println("Resized image could not be saved");
}
}

}

最佳答案

本文:Perils of Image.getScaledInstance推荐 Graphics.drawImage() 的缩放变体。

关于java - 我怎样才能使这个图像缩放器快速?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9272489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com