2013-09-26 30 views
0

我正尝试一个图像转换成一个矩阵,并将其转换回来,但2张图片是不同的: 它转换成一个矩阵:的Java的BufferedImage setRgb的getRGB,2个不同的结果

public int[][] getMatrixOfImage(BufferedImage bufferedImage) { 
    int width = bufferedImage.getWidth(null); 
    int height = bufferedImage.getHeight(null); 
    int[][] pixels = new int[width][height]; 
    for (int i = 0; i < width; i++) { 
     for (int j = 0; j < height; j++) { 
      pixels[i][j] = bufferedImage.getRGB(i, j); 
     } 
    } 

    return pixels; 
} 

和转换它放回一个BufferedImage:

public BufferedImage matrixToBufferedImage(int[][] matrix) { 
    int width=matrix[0].length; 
    int height=matrix.length; 
    BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE); 

    for (int i = 0; i < matrix.length; i++) { 
     for (int j = 0; j < matrix[0].length; j++) { 

      int pixel=matrix[i][j] <<24|matrix[i][j] <<16|matrix[i][j]<<8|matrix[i][j] ; 
      bufferedImage.setRGB(i, j, pixel); 
     } 
    } 
    return bufferedImage; 

} 

这个结果:

http://img59.imageshack.us/img59/5464/mt8a.png

谢谢!

+1

出于性能原因(每次调用都会导致昂贵的色彩空间计算),您应该避免使用getRGB/setRGB,可以通过BufferedImage的Raster访问图像后面的数组。 – lbalazscs

回答

2

你为什么这样做

int pixel=matrix[i][j] <<24|matrix[i][j] <<16|matrix[i][j]<<8|matrix[i][j]; 

,而不是仅仅

int pixel=matrix[i][j]; 

+0

这就是为什么我很愚蠢;) – Laren0815

+0

这是否意味着你的问题解决了? –

+0

这是解决方案,我会标记,当我有权限。 – Laren0815

相关问题