Close Menu
GeekBlog

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    What's Hot

    Quantum Immortality Is Going Viral as “the Most Horrifying Idea Ever.” Here’s Why Physicists Aren’t Losing Sleep.

    November 18, 2026

    Huawei Watch Air Leaks at 6.9mm: A Titanium Smartwatch Thinner Than a Fitness Band, With a 5-Day Battery

    November 18, 2026

    Grindr’s $120-a-Month Edge Tier Uses AI to Guess Who Will Reply. Its CEO Says Not Everyone Should Buy It.

    November 18, 2026
    Facebook
    GeekBlog
    • Home
    • Mobile
    • Tech News
    • Blog
    • Gaming
    • Smartwatch
    • How-To Guides
    • AI & Software
    Facebook
    GeekBlog
    Home»Blog»How to Display a JPEG Image in C++ (2026)
    Blog

    How to Display a JPEG Image in C++ (2026)

    Ethan CaldwellBy Ethan CaldwellSeptember 4, 202611 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Email Copy Link
    Colorful programming code on a computer screen
    Photo via Pexels
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link

    C++ cannot display a JPEG on its own. The standard library has no image decoder and no window, so displaying a picture always means two separate jobs: decode the JPEG into raw pixels, and put those pixels on the screen. The three practical combinations are stb_image plus SDL2 for a tiny dependency footprint, OpenCV when you are already doing image work, and Qt when you are building a real desktop application.

    Quick answer: For the smallest setup, drop stb_image.h into your project, load with stbi_load(path, &w, &h, &n, STBI_rgb_alpha), then create an SDL2 window, surface and texture from that buffer. Build with g++ -std=c++20 main.cpp -o main $(pkg-config --cflags --libs sdl2). If OpenCV is already a dependency, cv::imshow does the whole thing in three lines.

    Both complete programs below were compiled and run on Ubuntu 24.04 with GCC 13.3 against SDL2 2.30.0, stb_image 2.30 and OpenCV 4.6.0. Each loaded a real 320 by 240 JPEG, created a window, uploaded the texture and exited cleanly. The SDL2 program produced zero warnings under -Wall -Wextra. Headless runs used SDL_VIDEODRIVER=dummy and QT_QPA_PLATFORM=offscreen, which exercise the same code paths as a real display.

    Why this takes two libraries

    A JPEG file is entropy coded, quantized frequency data. Turning it into pixels needs a decoder. Getting those pixels onto a monitor needs a window from the operating system and a way to hand the buffer to the compositor or the GPU. Nothing in the C++ standard covers either half.

    StackDecoderWindowDependency weightBest for
    stb_image plus SDL2One header fileSDL2LightGames, tools, anything portable
    OpenCVBuilt inBuilt in highguiHeavyComputer vision, quick debugging
    QtBuilt in image pluginsFull widget toolkitHeavyDesktop applications with a real UI
    libjpeg-turbo plus your own windowlibjpeg-turboYoursLight but manualMaximum decode speed

    Method 1: stb_image plus SDL2

    This is the setup with the fewest moving parts. stb_image.h is a single public domain header you copy into your tree; define STB_IMAGE_IMPLEMENTATION in exactly one translation unit before including it.

    sudo apt install libsdl2-dev
    curl -sSL -o stb_image.h https://raw.githubusercontent.com/nothings/stb/master/stb_image.h
    pkg-config --modversion sdl2   # 2.30.0 on Ubuntu 24.04
    #include <SDL2/SDL.h>
    #include <cstdio>
    #include <cstdlib>
    
    #define STB_IMAGE_IMPLEMENTATION
    #include "stb_image.h"
    
    int main(int argc, char* argv[]) {
        if (argc < 2) {
            std::fprintf(stderr, "usage: %s image.jpg\n", argv[0]);
            return 1;
        }
    
        int w = 0, h = 0, channels = 0;
        unsigned char* pixels = stbi_load(argv[1], &w, &h, &channels, STBI_rgb_alpha);
        if (pixels == nullptr) {
            std::fprintf(stderr, "stbi_load failed: %s\n", stbi_failure_reason());
            return 1;
        }
        std::printf("loaded %dx%d, %d source channels\n", w, h, channels);
    
        if (SDL_Init(SDL_INIT_VIDEO) != 0) {
            std::fprintf(stderr, "SDL_Init: %s\n", SDL_GetError());
            stbi_image_free(pixels);
            return 1;
        }
    
        SDL_Window* window = SDL_CreateWindow("JPEG viewer",
            SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, w, h, SDL_WINDOW_SHOWN);
        SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    
        SDL_Surface* surface = SDL_CreateRGBSurfaceWithFormatFrom(
            pixels, w, h, 32, w * 4, SDL_PIXELFORMAT_RGBA32);
        SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
    
        bool running = true;
        while (running) {
            SDL_Event e;
            while (SDL_PollEvent(&e)) {
                if (e.type == SDL_QUIT ||
                    (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE)) {
                    running = false;
                }
            }
            SDL_RenderClear(renderer);
            SDL_RenderCopy(renderer, texture, nullptr, nullptr);
            SDL_RenderPresent(renderer);
            SDL_Delay(16);
        }
    
        SDL_DestroyTexture(texture);
        SDL_FreeSurface(surface);
        stbi_image_free(pixels);
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        SDL_Quit();
        return 0;
    }
    g++ -std=c++20 -Wall -Wextra viewer.cpp -o viewer $(pkg-config --cflags --libs sdl2)
    ./viewer photo.jpg
    # loaded 320x240, 3 source channels

    Recommended for you:

    Can You Use Movie Clips in YouTube Videos? What the Law Actually Says
    Blog·Sep 3, 2026

    Can You Use Movie Clips in YouTube Videos? What the Law Actually Says

    Four details make this work. Requesting STBI_rgb_alpha forces four channels out regardless of what the file contained, so the stride arithmetic w * 4 is always correct. SDL_PIXELFORMAT_RGBA32 is an endianness aware alias, so the same code is right on a big endian machine. SDL_CreateRGBSurfaceWithFormatFrom does not copy, it wraps your buffer, which is why stbi_image_free must come after the texture is built. And the SDL_Delay(16) keeps the poll loop from spinning a core at 100 percent.

    Warning: The surface borrows the stb buffer rather than owning it. Calling stbi_image_free(pixels) before SDL_CreateTextureFromSurface gives you a use after free, which typically renders garbage on one machine and crashes on another. Free the pixels only after the texture exists, since the texture holds its own GPU side copy.

    Method 2: OpenCV imshow

    If OpenCV is already in your build, this is three lines of real work. The decode, the window and the event loop are all handled for you.

    #include <opencv2/core.hpp>
    #include <opencv2/imgcodecs.hpp>
    #include <opencv2/highgui.hpp>
    #include <iostream>
    
    int main(int argc, char** argv) {
        if (argc < 2) {
            std::cerr << "usage: " << argv[0] << " image.jpg\n";
            return 1;
        }
    
        cv::Mat image = cv::imread(argv[1], cv::IMREAD_COLOR);
        if (image.empty()) {
            std::cerr << "could not read " << argv[1] << '\n';
            return 1;
        }
    
        std::cout << "size " << image.cols << "x" << image.rows
                  << ", channels " << image.channels() << '\n';
    
        cv::namedWindow("JPEG viewer", cv::WINDOW_AUTOSIZE);
        cv::imshow("JPEG viewer", image);
        cv::waitKey(0);
        cv::destroyAllWindows();
        return 0;
    }
    sudo apt install libopencv-dev
    
    g++ -std=c++20 -Wall -Wextra ocv.cpp -o ocv \
        -I/usr/include/opencv4 -lopencv_core -lopencv_imgcodecs -lopencv_highgui
    
    ./ocv photo.jpg
    # size 320x240, channels 3
    Note: Building this against the OpenCV 4.6.0 packaged with Ubuntu 24.04 produced dozens of -Wdeprecated-enum-enum-conversion warnings, all of them from OpenCV’s own headers rather than from my source. That noise comes from C++20 tightening enum arithmetic rules and is fixed in later OpenCV releases; the current line is OpenCV 5.0. If you are stuck on the packaged version, silence it locally with -Wno-deprecated-enum-enum-conversion rather than dropping -Wall.

    Note that cv::imread gives you BGR channel order, not RGB. That is a long standing OpenCV convention. It does not matter for imshow, which expects BGR, but the moment you hand that buffer to any other library you need cv::cvtColor(image, out, cv::COLOR_BGR2RGB).

    Method 3: Qt with QLabel and QPixmap

    When the picture belongs inside a real application with menus and layouts, Qt is the right answer. Its image plugins handle JPEG, PNG and more without a separate decoder.

    #include <QApplication>
    #include <QLabel>
    #include <QPixmap>
    
    int main(int argc, char* argv[]) {
        QApplication app(argc, argv);
    
        QPixmap pixmap(argc > 1 ? argv[1] : "photo.jpg");
        if (pixmap.isNull()) {
            return 1;
        }
    
        QLabel label;
        label.setPixmap(pixmap);
        label.setScaledContents(false);
        label.setWindowTitle("JPEG viewer");
        label.resize(pixmap.size());
        label.show();
    
        return app.exec();
    }
    # viewer.pro
    QT += widgets
    SOURCES += main.cpp
    CONFIG += c++20
    
    qmake && make
    ./viewer photo.jpg

    To be clear about what was verified: unlike the SDL2 and OpenCV programs above, this Qt example was not compiled in the environment used for this guide, because the Qt development packages were not installed there. The API calls are straight from the documented QPixmap and QLabel interfaces, but treat the build command as a starting point rather than a tested recipe. Qt Widgets requires the qtbase5-dev or qt6-base-dev package depending on which major version you target.

    Decoding without displaying

    Half the time you do not want a window at all: you want the pixels, to resize a thumbnail, compute an average color or feed a model. stb_image alone covers that, with no SDL2 and no linking beyond the standard library.

    #include <cstdio>
    #define STB_IMAGE_IMPLEMENTATION
    #include "stb_image.h"
    
    int main(int argc, char* argv[]) {
        if (argc < 2) {
            std::fprintf(stderr, "usage: %s image.jpg
    ", argv[0]);
            return 1;
        }
    
        int w = 0, h = 0, n = 0;
        if (!stbi_info(argv[1], &w, &h, &n)) {
            std::fprintf(stderr, "not a readable image: %s
    ", stbi_failure_reason());
            return 1;
        }
        std::printf("header says %dx%d, %d channels
    ", w, h, n);
    
        unsigned char* px = stbi_load(argv[1], &w, &h, &n, STBI_rgb_alpha);
        if (px == nullptr) {
            std::fprintf(stderr, "decode failed: %s
    ", stbi_failure_reason());
            return 1;
        }
    
        long long r = 0, g = 0, b = 0;
        const long long count = static_cast<long long>(w) * h;
        for (long long i = 0; i < count; ++i) {
            r += px[i * 4 + 0];
            g += px[i * 4 + 1];
            b += px[i * 4 + 2];
        }
        std::printf("average RGB %lld %lld %lld
    ", r / count, g / count, b / count);
    
        stbi_image_free(px);
        return 0;
    }
    g++ -std=c++20 -Wall -Wextra decode.cpp -o decode
    ./decode photo.jpg
    # header says 320x240, 3 channels
    # average RGB 108 119 128

    stbi_info reads only the header, so you can validate dimensions and reject an absurdly large image before committing to the allocation. That is worth doing on any file you did not create yourself: a crafted JPEG claiming to be 60000 by 60000 pixels asks for roughly 14 GB at four bytes per pixel.

    Scaling the image to fit the window

    A photograph from a phone is larger than most screens, so a viewer that opens a window the size of the image is not useful. Each stack handles this differently.

    // SDL2: give RenderCopy a destination rectangle
    SDL_Rect dst{0, 0, 800, 600};
    SDL_RenderCopy(renderer, texture, nullptr, &dst);
    
    // SDL2, letterboxed automatically
    SDL_RenderSetLogicalSize(renderer, w, h);
    
    // OpenCV: resize the Mat, or use a resizable window
    cv::resize(image, small, cv::Size(), 0.5, 0.5, cv::INTER_AREA);
    cv::namedWindow("JPEG viewer", cv::WINDOW_NORMAL);
    
    // Qt: scale the pixmap, keeping the aspect ratio
    label.setPixmap(pixmap.scaled(800, 600, Qt::KeepAspectRatio,
                                  Qt::SmoothTransformation));

    Use cv::INTER_AREA when shrinking and cv::INTER_CUBIC when enlarging. For SDL2, SDL_RenderSetLogicalSize is usually what you want because it letterboxes rather than stretching, so the aspect ratio survives a window resize with no arithmetic on your part.

    Troubleshooting

    stbi_load returns null. Call stbi_failure_reason(), which explains whether the file was missing, truncated or in an unsupported variant. stb_image handles baseline and progressive JPEG but not arithmetic coded or CMYK files, which come out of some print workflows.

    undefined reference to stbi_load. You included the header without defining STB_IMAGE_IMPLEMENTATION, or you defined it in more than one translation unit and got duplicate symbols instead. Define it in exactly one .cpp file, immediately before the include.

    The window opens black or shows garbage. The stride is wrong or the pixel buffer was freed too early. Pass w * 4 as the pitch and request STBI_rgb_alpha so there are always four bytes per pixel, and free the buffer only after the texture is created.

    Colors are swapped, blue where red should be. You mixed RGB and BGR. OpenCV reads BGR, stb_image gives RGB. Convert with cv::cvtColor, or pick the matching SDL pixel format constant rather than reordering bytes by hand.

    Recommended for you:

    Why Is Jack the Black Cat Squishmallow So Rare?
    Blog·Sep 3, 2026

    Why Is Jack the Black Cat Squishmallow So Rare?

    Qt fails with no platform plugin, or SDL fails to open a display. There is no display available, which is normal over SSH or in a container. Set QT_QPA_PLATFORM=offscreen or SDL_VIDEODRIVER=dummy to exercise the code path in a test, or forward X11 to see the actual window.

    Frequently asked questions

    Can I display a JPEG with only the standard library?

    No. The C++ standard library has no image decoding and no windowing. Every approach requires a third party library for at least one of the two halves. That is unlikely to change; no proposal for either capability is near standardization.

    Which method is lightest?

    stb_image plus SDL2. stb_image is one header you copy into your source tree with no build system changes, and SDL2 is a single small shared library available in every package manager. OpenCV and Qt each pull in tens of megabytes of dependencies.

    Should I use SDL2 or SDL3 for new code?

    SDL3 is the current major line, with 3.4.0 released in January 2026, and it is where new development happens. The API differs enough that the code above will not compile unchanged. SDL2 remains widely packaged and is a reasonable choice if you want the version your distribution ships today.

    Do I need SDL2_image if I already have stb_image?

    No, they overlap. SDL2_image wraps libjpeg and libpng and returns an SDL_Surface directly, which is slightly less code. stb_image avoids the extra dependency entirely and gives you a plain byte buffer you can hand to any renderer, including OpenGL or Vulkan.

    How do I display an image loaded from memory rather than a file?

    All three support it. Use stbi_load_from_memory(buffer, length, ...), or cv::imdecode(cv::Mat(1, length, CV_8UC1, buffer), cv::IMREAD_COLOR), or QPixmap::loadFromData. This is what you want when the JPEG arrives over a network rather than from disk.

    The bottom line

    Decode and display are two separate problems, and once you see that, the choice is easy. Reach for stb_image plus SDL2 unless something else in your project already drags in OpenCV or Qt, in which case use what you have rather than adding a fourth dependency.

    The two bugs that catch almost everyone are freeing the pixel buffer before the texture is built, and mixing up RGB with BGR. Both are silent: no error, just a black window or a blue sky that came out orange. Check those first. For more C++ fundamentals, see our guides on writing a file in C++, joining two vectors in C++ and using threads in C++, which matters here because decoding a large image off the UI thread is what keeps a viewer responsive. The SDL2 wiki documents every function used above.

    About this article: GeekBlog covers U.S. technology news, AI, phones, smartwatches and gaming. Every story is written and checked under our Editorial Policy. Spotted a mistake or have a story tip? Contact our editors.

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Telegram Email Copy Link
    Previous ArticleWhat Is the Arms Index (TRIN)? Formula and Signals
    Next Article How to Trade With the Money Flow Index (MFI)
    Ethan Caldwell

      Ethan Caldwell is GeekBlog's resident Apple specialist, covering the entire Apple ecosystem: iPhone, iPad, Mac, Apple Watch, AirPods and the software that ties them together. A longtime iOS user and gadget collector, Ethan tracks Cupertino's every move, breaking down Apple keynotes, A- and M-series chip benchmarks, iOS feature updates and the rumor mill into clear, practical takes that help readers decide whether the latest Apple hardware is worth the upgrade.

      Related Posts

      10 Mins Read

      Google Ads Keyword Planner: How It Shows the Most Relevant Keywords

      11 Mins Read

      How to Use Remarketing Techniques for Better Conversions

      11 Mins Read

      How to Conduct A/B Testing for Marketing Campaigns

      10 Mins Read

      AMP for WP Plugin Vulnerability: What Was Fixed and What to Do

      11 Mins Read

      How to Create a Facebook Business Page in 2026

      11 Mins Read

      How to Convert GMT Time to Other Time Zones in C++

      Top Posts

      Every iPhone Camera Ranked in 2026 (Best to Worst)

      July 6, 2026386 Views

      Best Browser for Android in 2026: Top Picks Ranked

      July 7, 2026258 Views

      iPhone Battery Replacement Cost: Every Model, Apple vs Repair Shop

      October 6, 2026200 Views
      Stay In Touch
      • Facebook

      Subscribe to Updates

      Get the latest tech news from FooBar about tech, design and biz.

      Most Popular

      Apple Told Its Stores Not to Expect iPhone Duo Walk-Ins. Carriers Can Beat January by Weeks.

      October 20, 2026317 Views

      Apple Watch Black Friday 2026: Early Deals, Prices to Beat and When to Buy

      November 8, 2026265 Views

      One UI 9 Watch: Which Galaxy Watches Get Wear OS 7, and Who Gets Left Behind

      November 6, 2026170 Views
      Our Picks

      Quantum Immortality Is Going Viral as “the Most Horrifying Idea Ever.” Here’s Why Physicists Aren’t Losing Sleep.

      November 18, 2026

      Huawei Watch Air Leaks at 6.9mm: A Titanium Smartwatch Thinner Than a Fitness Band, With a 5-Day Battery

      November 18, 2026

      Grindr’s $120-a-Month Edge Tier Uses AI to Guess Who Will Reply. Its CEO Says Not Everyone Should Buy It.

      November 18, 2026

      Subscribe to Updates

      Get the latest creative news from FooBar about art, design and business.

      HEICJPG.online - Convert HEIC to JPG online
      Facebook
      • About GeekBlog: Our Mission, Team and Editorial Standards
      • Contact us
      • Privacy Policy
      • Disclaimer
      • Terms and Conditions
      • Editorial Policy
      • Cookie Policy
      • Your Privacy Choices
      © 2026 GeekBlog

      Type above and press Enter to search. Press Esc to cancel.