【问题标题】:how to display picture in java with giving R,G,B如何在java中显示图片并给出R,G,B
【发布时间】:2013-09-29 17:18:13
【问题描述】:

R 或 G 或 B 的值存储在 int 中,范围为 0~255。 我已经有了图片每个像素的所有 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,我应该将其转换为字节吗?如果是,怎么办,如果不是,有没有其他方法来计算pix? 我知道有人用

         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 存储在字节类型中

【问题讨论】:

    标签: java c++ image byte rgb


    【解决方案1】:

    BufferedReader 类通过getRGB() 方法返回一个或一个像素列表,我不得不提一下,您不会将它作为像 int[width][height] 这样的 2 位数组,例如,如果您请求从 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

    【讨论】:

    • 我不想获取图片的 rgb,但我知道像素的每个 rgb,并且想要显示这个
    • @Rebecca 欢迎您,我不得不说我错过了一些代码(请检查更新的答案),我希望您已经很好地解决了这个问题。问题是,在通过wrap() 方法将 byte[] 数组包装到 int 中之后,您也必须调用我错过的getInt() 方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    • 1970-01-01
    • 2018-01-10
    • 1970-01-01
    • 2020-06-10
    相关资源
    最近更新 更多