Search code examples
c++boostboost-gil

How to flip image vertically using Boost::GIL


I'm trying to generate an image icon. Based on some restrictions, I need to get a one-dimensional array of int32_t pixel values ​​in order {r, g, b, a, r1, g1, b1, a1, ...}. In this case, the order of the rows should be the same as with OpenGL UV (bottom to top). For this, I used the following, verified, it works:

const int image_width = image.width();
const int image_height = image.height();
if (!(image_width && image_height)) { return 1; }

int preview_width, preview_height;
if (image_width > image_height) {
    preview_width = PREVIEW_SIZE;
    preview_height = PREVIEW_SIZE * (float)image_height / (float)image_width;
}
else {
    preview_width = PREVIEW_SIZE * (float)image_width / (float)image_height;
    preview_height = PREVIEW_SIZE;
}

bg::rgba8_image_t preview_square(preview_width, preview_height);
const bg::rgba8_view_t& ps_viewer = bg::view(preview_square);
bg::resize_view(bg::const_view(image), ps_viewer, bg::bilinear_sampler());

std::vector<int32_t> arr(preview_width * preview_height);
memcpy(&arr[0], &ps_viewer[0], sizeof(int32_t) * arr.size());

Based on the storage order of pixels in the GIL, I need to flip the image along the y-axis. Please tell me how to implement this?

enter image description here


Solution

  • You can use a flipped view to do the transform:

    #include <boost/gil.hpp>
    #include <boost/gil/algorithm.hpp>
    #include <boost/gil/dynamic_step.hpp>
    #include <boost/gil/extension/io/jpeg.hpp>
    #include <boost/gil/extension/io/png.hpp>
    
    namespace bg = boost::gil;
    
    int main() {
        bg::rgba8_image_t v;
        bg::read_and_convert_image("/tmp/VIplm.jpg", v, bg::jpeg_tag{});
    
        using Pixel = bg::rgba8_pixel_t;
        std::vector<Pixel> vec(v.width() * v.height());
    
        auto dest = bg::interleaved_view(v.width(), v.height(), vec.data(), v.width() * sizeof(Pixel));
        bg::copy_and_convert_pixels(
            bg::flipped_left_right_view(bg::const_view(v)),
            dest);
    
        bg::write_view("/tmp/pixels.png", dest, bg::png_tag{});
    }
    

    The png is here:

    enter image description here

    I left out the resize operation.