Search code examples
c++sfml

mirror half an image c++


so i am trying to mirror an image although only half of it so that my image(a zebra) only has either two butts or two heads, it really doesn't matter which. i managed to gray scale half the picture with the code i have below. How should i do to mirror it instead of making it gray?

int main()
{
    sf::Image image;
    image.loadFromFile("../Images/zebra.bmp"); 
    sf::Color greyscale(0, 0, 0, 255);
    sf::Color newPixelColor;

    sf::RenderWindow window(sf::VideoMode(image.getSize().x, image.getSize().y), "Image manipulation");
    sf::Texture imageTexture;
    imageTexture.loadFromImage(image);

    sf::RectangleShape picture;

    picture.setSize(sf::Vector2f((float)image.getSize().x, (float)image.getSize().y));
    picture.setTexture(&imageTexture);

    sf::Event event;

    while (window.isOpen())
    {
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
            {
                window.close();
            }
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
        {
            for (int x = 0; x < image.getSize().x; x++) {
                for (int y = 0; y < image.getSize().y; y++) {
                    if(x > (image.getSize().x) / 2) {
                        int newPixel = image.getPixel(x, y).r;
                        newPixel = image.getPixel(x, y).g;
                        newPixel = image.getPixel(x, y).b;

                        newPixelColor.r = newPixel;
                        newPixelColor.g = newPixel;
                        newPixelColor.b = newPixel;

                        image.setPixel(x, y, newPixelColor);
                    }
                }
            }
            imageTexture.loadFromImage(image);
        }
        window.clear();
        window.draw(picture);
        window.display();
    }
    return 0;
}`

Solution

  • so for those who want the answer. Change y with x and x with y and you will get what i was looking for!

    int halfHeight = image.getSize().y / 2;
    
    for (int y = 0; y < halfHeight; y++)
    {
        for (int x = 0; x < image.getSize().x; x++)
        {
            image.setPixel(x, image.getSize().y - 1 - y, image.getPixel(x, y));
        }
    }