简体   繁体   中英

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

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!

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.

    public void mirror(boolean flipHorizontally, boolean flipVertically) {
        
        byte[] pixels = new byte[imageBuffer.capacity()];
        
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int offset = NNGINEUtil.offset(x, y, width);
                
                int flipX = (flipHorizontally ? (width - 1) - x : x);
                int flipY = (flipVertically ? (height - 1) -  y: y);
                
                int invOffset = NNGINEUtil.offset(flipX, flipY, width);
                
                byte r = imageBuffer.get(invOffset + 0);
                byte g = imageBuffer.get(invOffset + 1);
                byte b = imageBuffer.get(invOffset + 2);
                byte a = imageBuffer.get(invOffset + 3);
                
                pixels[offset + 0] = r;
                pixels[offset + 1] = g;
                pixels[offset + 2] = b;
                pixels[offset + 3] = a;
            }
        }
        
        imageBuffer = ByteBuffer.wrap(pixels);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM