Reputation: 4777
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"));
Upvotes: 4
Views: 769