在Java中高效访问图像像素 [英] Efficient access to image pixels in Java

查看:141
本文介绍了在Java中高效访问图像像素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个重采样函数,它接受输入图像并用Java生成输出图像。

I need to write a resampling function that takes an input image and generates an output image in Java.

图像类型为TYPE_BYTE_GRAY。

The image type is TYPE_BYTE_GRAY.

由于所有像素都将被读取和写入,我需要一种有效的方法来访问图像缓冲区。

As all pixels will be read and written, I need an efficient method to access the image buffer(s).

我不喜欢相信像getRGB / setRGB这样的方法是合适的,因为它们会执行转换。我正在使用能够最直接访问存储缓冲区的函数,具有高效的地址计算,无图像复制和最小开销。

I don't trust that methods like getRGB/setRGB will be appropriate as they will perform conversions. I am after functions that will allow me the most direct access to the stored buffer, with efficient address computation, no image copy and minimum overhead.

你能帮助我吗?我找到了很多种类的例子,例如使用WritableRaster,但没有足够的完整。

Can you help me ? I have found examples of many kinds, for instance using a WritableRaster, but nothing sufficiently complete.

更新

根据@FiReTiTi的建议,诀窍是从图像中获取 WritableRaster 并获取其关联缓冲区为 DataBufferByte 对象。

As suggested by @FiReTiTi, the trick is to get a WritableRaster from the image and get its associated buffer as a DataBufferByte object.

DataBufferByte SrcBuffer= (DataBufferByte)Src.getRaster().getDataBuffer();

然后你可以选择使用 getElem直接访问缓冲区 / setElem methods

Then you have the option to directly access the buffer using its getElem/setElem methods

SrcBuffer.setElem(i, getElem(i) + 1);

或提取字节数组

byte [] SrcBytes= SrcBuffer.getData();
SrcBytes[i]= SrcBytes[i] + 1;

这两种方法都有效。我还不知道它的性能有什么不同...

Both methods work. I don't know yet it there's a difference in performance...

推荐答案

最简单的方法(但不是最快)是使用Raster myimage.getRaster(),然后使用方法 getSample(x,y,c) setSample(x,y,c,v)访问和修改像素值。

The easiest way (but not the fastest) is to use the Raster myimage.getRaster(), and then use the methods getSample(x,y,c) and setSample(x,y,c,v) to access and modify the pixels values.

最快的方式这是访问DataBuffer(直接访问代表图像的数组),因此对于TYPE_BYTE_GRAY BufferedImage,它将是 byte [] buffer =((DataBufferByte)myimage.getRaster()。getDataBuffer( ))。的getData()。请注意,像素在 byte 上编码而不是无符号字节,因此每次要读取像素时值,你必须做 buffer [x]& 0xFF

The fastest way to do it is to access the DataBuffer (direct access to the array representing the image), so for a TYPE_BYTE_GRAY BufferedImage, it would be byte[] buffer = ((DataBufferByte)myimage.getRaster().getDataBuffer()).getData(). Just be careful that the pixels are encoded on byte and not unsigned byte, so every time you want to read a pixel value, you have to do buffer[x] & 0xFF.

这是一个简单的测试:

BufferedImage image = new BufferedImage(256, 256, BufferedImage.TYPE_BYTE_GRAY) ;
byte[] buffer = ((DataBufferByte)image.getRaster().getDataBuffer()).getData() ;
System.out.println("buffer[0] = " + (buffer[0] & 0xFF)) ;
buffer[0] = 1 ;
System.out.println("buffer[0] = " + (buffer[0] & 0xFF)) ;

这是输出:

buffer[0] = 0
buffer[0] = 1

这篇关于在Java中高效访问图像像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆