在 Java 中垂直翻转原始图像
我需要在 Java 中翻转一个原始图像,该图像的行已反转。我所说的倒置是指图像的第一行存储在文件的末尾。
我设法通过使用辅助缓冲区对图像行重新排序来实现我想要的效果。我在下面包含了我的代码。
我认为这可以通过翻译坐标来优化,避免内存复制。我尝试实现一个可以反转行的 DataBuffer,但我使用的栅格需要 DataBufferByte (最终类)。
有谁知道更优化的方式来做我想做的事?
谢谢
...
int w = 640;
int h = 480;
byte[] flippedData = new byte[640*480*4];
int scanLineLength = w*4;
for(int i=0;i!=h; ++i) {
System.arraycopy(originalData, scanLineLength*i, flippedData, scanLineLength*(h-i)-scanLineLength, scanLineLength);
}
DataBuffer db = new DataBufferByte(flippedData,flippedData.length);
WritableRaster raster = Raster.createInterleavedRaster(db, w, h, scanLineLength, 4, new int[]{2,1,0}, new Point(0,0));
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
ColorModel cm = new ComponentColorModel(cs, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
BufferedImage img = new BufferedImage(cm, raster, false, null);
ImageIO.write(img, "JPEG", new File("out.jpg"));
I need to flip in Java a raw image that has her rows inverted. By inverted I mean, the first row of the image is stored at the end of a file.
I managed to achive what I want by reordering the image rows using an auxiliar buffer. I included my code below.
I think this can be optimized by translating the coordinates, avoiding the memory copy. I tried to implement a DataBuffer that would invert the rows, but the raster I'm using requires a DataBufferByte (a final class).
Does anyone knows a more optimized way of doing what I want?
Thank you
...
int w = 640;
int h = 480;
byte[] flippedData = new byte[640*480*4];
int scanLineLength = w*4;
for(int i=0;i!=h; ++i) {
System.arraycopy(originalData, scanLineLength*i, flippedData, scanLineLength*(h-i)-scanLineLength, scanLineLength);
}
DataBuffer db = new DataBufferByte(flippedData,flippedData.length);
WritableRaster raster = Raster.createInterleavedRaster(db, w, h, scanLineLength, 4, new int[]{2,1,0}, new Point(0,0));
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
ColorModel cm = new ComponentColorModel(cs, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
BufferedImage img = new BufferedImage(cm, raster, false, null);
ImageIO.write(img, "JPEG", new File("out.jpg"));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
java.awt.AffineTransform
:
请参阅此和this 查看如何使用
AffineTransform
实现翻转Use
java.awt.AffineTransform
:See this and this to see how is flipping implemented using
AffineTransform