我需要能够以特定分辨率将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的'convert'缩小尺寸,然后以这种方式加载缩小版本。这节省了额外的33%。
我想知道,如果有更好的方法。
编辑:我意识到有些人会想知道我的代码是否总体上是好的,答案是肯定的。我使用的代码对我很有用,因为我缩小了已经很小的图像(比如640x480,否则.getRGB()需要永远)而且我不在乎是否有几个颜色点溢出(来自添加的结转) ,我知道有些人真正关心这一点。答案 0 :(得分:3)
这是一篇关于以最佳方式在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);