Flip/Mirror the contents of ByteBuffer (Image Buffer) horizontally/vertically

Viewed 72

I'm storing an image in a Java ByteBuffer object. I'm fetching each coordinate with a basic offset function like this:

    public static int offset(int x, int y, int z, int width, int height) {
        return (z * height + y) * width + x;
    }

And you can get the colors like so:

        int r = imageBuffer.get(offset + 0) & 0xFF; //0xFF is the hexadecimal way of writing 255, turns this byte into an unsigned byte
        int g = imageBuffer.get(offset + 1) & 0xFF;
        int b = imageBuffer.get(offset + 2) & 0xFF;
        int a = imageBuffer.get(offset + 3) & 0xFF;

I want to flip the image in the ByteBuffer horizontally/vertically, but most of my searches turn up queries on flip(). I was wondering if this is even possible with just the ByteBuffer, or if I'm going to have to come up with a more complex solution? It needs to still be a ByteBuffer by the ending of my processing.

Here is the information I have available:

    private ByteBuffer imageBuffer;
    private int imageWidth, imageHeight;

Any help is appreciated! Thank you for your time!

1 Answers

No worries! I managed to do it myself. Just make a byte array copy and then write a new bytebuffer with that to get the desired result.

Edit: Simplified Function

public Image4C mirror(boolean flipHorizontally, boolean flipVertically) {
    
    if (!flipHorizontally && !flipVertically) {
        return this;
    }
    
    ByteBuffer outputBuffer = ByteBuffer.allocate(width * height * CHANNELS);
    
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            int offset = NNGINEUtil.offset(x, y, width, CHANNELS);
            
            int flipX = (flipHorizontally ? (width - 1) - x : x);
            int flipY = (flipVertically ? (height - 1) -  y: y);
            
            int invOffset = NNGINEUtil.offset(flipX, flipY, width, CHANNELS);
            
            for (int i = 0; i < CHANNELS; i++) {
                outputBuffer.put(offset + i, imageBuffer.get(invOffset + i));
            }
        }
    }
    
    imageBuffer = outputBuffer;
    
    return this;
}

Where NNGINEUtil.offset() is:

public static int offset(int x, int y, int w, int channels) {
    return (y * w + x) * channels;
}
Related