R或G或B的值存储在0~255的int中。 我已经有了图片每个像素的所有 rgb 值,我想根据我已经知道的 r、g、b 显示图片。
BufferedImage imgnew = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
//I can get access to the rgb of every pixel by R[x][y],G[x][y],B[x][y]
//how to calculate the rgb of every pixel?
imgnew.setRGB(x, y, rgb);
}
}
JFrame frame = new JFrame();
JLabel labelnew = new JLabel(new ImageIcon(imgnew));
frame.getContentPane().add(labelnew, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
我的问题是如何计算每个像素的正确像素,因为 rgb 存储为 int,我应该将它转换为字节吗?如果是,怎么办,如果不是,还有其他方法可以计算像素吗? 我知道有人用
int rgb = 0xff000000 | ((R[x][y] & 0xff) << 16) | (((G[x][y] & 0xff)<< 8) | ((B[x][y] & 0xff);//the way I calcualte the pix is wrong, which lead to the wrong color of pics
计算rgb,但是这里的R[x][y] G,B是以bytes类型存储的
最佳答案
BufferedReader
类通过 getRGB()
方法返回一个或像素列表,我不得不提一下,您不会将它作为二维数组获取像 int[width][height],例如,如果你请求从 0,0 到 10,20 的像素,那么你将得到一个 200 长度的 int[] 数组。
然后您需要将每个 int 值分解为 4 个字节,代表每个像素的 (argb),因此您可以使用 ByteBuffer
类来完成。
这里是一个简单的例子
int imgWidth=1920,imgHeight=1080;
int[] row=new int[imgWidth];//for storing a line of pixels
for(int i=0;i<imgHeight;i++){
row=img.getRGB(0,i,imgWidth,1,null,0,imgWidth);//get pixel from the current row
for(int k=0;k<row.length;k++){
byte[] argb=ByteBuffer.allocate(4).putInt(4).array();//break up int(color) to 4 byte (argb)
//doing some business with pixel....
}
//setting the processed pixel
//////////////////////////////////////////UPDATED!
//Preparing each pixel using ByteBuffer class, make an int(pixel) using a 4-lenght byte array
int rgb=ByteBuffer.wrap(new byte[]{0xff,R[x][y]&0xff,G[x][y]&0xff,B[x][y]&0xff}).getInt();
imgnew.setRGB(x,y,rgb);//this is bettrer to buffer some pixel then set it to the image, instead of set one-by-one
//////////////////////////////////////////
//img.setRGB(0,i,imgWidth,1,row,0,imgWidth)
}
同时检查这个example也是
关于java - 如何用给定的R,G,B在java中显示图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19080951/