Java 灰度缓冲图像

标签 java image bufferedimage grayscale

所以我有一个表示像素数据(8 位灰度)的字节数组。没有标题。没什么。只是数据。我想根据这些数据创建一个缓冲图像。我做到了

image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
image.getRaster().setDataElements(0, 0, w, h, data);
this.x = w;
this.y = h;
scalemode=false;
exactmode=true;

其中 w 是像素宽度,h 是像素高度,data 是字节数组,图像是 BufferedImage

这是我的绘画方法

 protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;

        int rx = (this.getWidth() - x) / 2;
        int ry = (this.getHeight() - y) / 2;

        g2d.drawImage(image, rx, ry,x,y, null);
    }

但是,我得到了这张图像(真实图像是指纹,主要是白色像素)

messed up image

出了什么问题?我尝试按原样保存数据,然后在 Photoshop 中查看。数据没问题。

[编辑] 别介意这个问题。我在代码的其他部分搞砸了并且没有意识到。感谢您的所有投入

最佳答案

很难确切知道出了什么问题,因为您没有发布足够的信息。我们不知道 wh 或您的数据中包含哪些信息。我们不知道图像应该是什么样子。

但是,这里有一些代码几乎完全符合您正在做的事情,并且它对我有用:

// Set up h/w and backing data
int w = 300;
int h = 200;
byte[] data = new byte[w * h];

// Create a smooth gradient
for (int y = 0; y < h; y++) {
    int off = y * w;

    for (int x = 0; x < w; x++) {
        data[off + x] = (byte) (Math.round((x / (double) w) * 127) 
                              + Math.round((y / (double) h) * 127));
    }
}

// Create BufferedImage from data
final BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
image.getRaster().setDataElements(0, 0, w, h, data);

// Show it all in a window
SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        JFrame frame = new JFrame(getClass().getSimpleName());
        frame.add(new JLabel(new ImageIcon(image)));

        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
});

结果如下:

Image of JFrame from above code

关于Java 灰度缓冲图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32109428/

相关文章:

java - 从网页打开文件夹/资源管理器客户端的方法.... Java 小程序?

Java Instant 的 bug? `DateTimeException: Invalid value for Year`

javascript - 使用脚本更改元素的尺寸

java - 使用BufferedImage绘制Mandelbrot集,只得到纯色

Java,缓冲图像的颜色与原始图像完全不同

java - 如何在另一个类的不同包中创建一个类的对象

java - 如何在 JUnit4 中按特定顺序运行测试方法?

image - 尝试使用opencv使Photoshop达到色彩平衡

javascript - 将一个图像淡入另一个图像

java - ImageJ 与 BufferedImage 的兼容性