如何快速制作此图像缩放器?

时间:2012-02-14 06:09:01

标签: java performance

这是我当前的ImageResizer类。

当你需要处理100k图像时,每张图像目前大约需要0.4秒,这非常慢。

请告诉我如何使用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");
    }
}

}

2 个答案:

答案 0 :(得分:1)

本文:Perils of Image.getScaledInstance建议使用Graphics.drawImage()的缩放变体。

答案 1 :(得分:0)

你对这些尺码有一些自由吗?然后使用2的幂大小的图像,和\或使用2的倍数(至少整数)的缩放比例。这是一个通用的算法建议,因为我不熟悉Java图像库。

相关问题