java - 将缩略图像素值加载到 Java 中的最快方法

标签 java imagemagick thumbnails

我需要能够将特定分辨率的 RGB 像素值加载到 Java 中。该分辨率很小(~300x300)。

目前,我一直这样加载它们:

File file = new File("...path...");     
BufferedImage imsrc = ImageIO.read(file);
int width = imsrc.getWidth();
int height = imsrc.getHeight();     
int[] data = new int[width * height];       
imsrc.getRGB(0,0, width, height, data, 0, width);

然后自己缩小尺寸。

Sam 要求缩小代码,所以这里是:

/**
 * DownSize an image. 
 * This is NOT precise, and is noisy. 
 * However, this is fast and better than NearestNeighbor
 * @param pixels - _RGB pixel values for the original image
 * @param width - width of the original image
 * @param newWidth - width of the new image
 * @param newHeight - height of the new image
 * @return - _RGB pixel values of the resized image
 */
public static int[] downSize(int[] pixels, int width, int newWidth, int newHeight) {
    int height = pixels.length / width;
    if (newWidth == width && height == newHeight) return pixels;
    int[] resized = new int[newWidth * newHeight];
    float x_ratio = (float) width / newWidth;
    float y_ratio = (float) height / newHeight;
    float xhr = x_ratio / 2;
    float yhr = y_ratio / 2;
    int i, j, k, l, m;
    for (int x = 0; x < newWidth; x ++)
        for (int y = 0; y < newHeight; y ++) {              
            i = (int) (x * x_ratio);
            j = (int) (y * y_ratio);
            k = (int) (x * x_ratio + xhr);
            l = (int) (y * y_ratio + yhr);
            for (int p = 0; p < 3; p ++) {
                m = 0xFF << (p * 8);
                resized[x + y * newWidth] |= (
                        (pixels[i + j * width] & m) +
                        (pixels[k + j * width] & m) +
                        (pixels[i + l * width] & m) + 
                        (pixels[k + l * width] & m) >> 2) & m;
            }
        }
    return resized;
}

最近,我意识到我可以使用 ImageMagick 的“转换”缩小尺寸,然后以这种方式加载缩小尺寸的版本。这样可以额外节省 33%。

我想知道是否有更好的方法。

编辑:我意识到有些人会怀疑我的代码总体上是否良好,答案是否定的。我使用的代码对我来说效果很好,因为我缩小了已经很小的图像(比如 640x480,否则 .getRGB() 会永远占用)而且我不在乎是否有几个色点溢出(加法结转) ,我知道有些人真的很关心这一点。

最佳答案

这是一篇关于以最佳方式在 Java 中生成缩略图的非常好的文章:

http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html

指定不同的缩放/渲染参数可能会得到更好的结果。

    Graphics2D g2 = (Graphics2D)g;
    int newW = (int)(originalImage.getWidth() * xScaleFactor);
    int newH = (int)(originalImage.getHeight() * yScaleFactor);
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                        RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
    g2.drawImage(originalImage, 0, 0, newW, newH, null);

关于java - 将缩略图像素值加载到 Java 中的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4480790/

相关文章:

java - 使用 GAE 生成字符串 ObjectId

java - 使用最终变量实现循环

python - 从背景中分离人物

bash - 使用 ImageMagick 和许多图像制作 GIF 动画

FFMPEG 用于下载时失真的视频缩略图

html - 将不同尺寸的图像放在彼此下面

java - 这种方法以某种方式删除了我的文件内容,但没有明显的原因

java - Spring Controller - 将属性注入(inject) AbstracController

php - 如何使用 ImageMagick 替换图像中的白色矩形?

php - 如何使用 php gd 创建自定义缩略图