Search code examples
c++windowsvisual-c++uwpwindows-store-apps

Generate Image from generated byte array in UWP vc++


Reference with this Question & answer by @Decade Moon
How can i use that method for generate image from byte array instead of image file.
i tried like below but nothing works. no image are shown

std::vector<char> data= std::vector<char>(imgx->Height * imgx->Width * 4);
    int offset;
    for (int row = 0; row < imgx->Height; row++)
    {
        for (int col = 0; col < imgx->Width; col++)
        {
            offset = (row * (int)(imgx->Width * 4)) + (col * 4);
            data[offset] = 0x58;      // Red
            data[offset + 1] = 0x58;  // Green
            data[offset + 2] = 0x58;  // Blue
            data[offset + 3] = 0x58;  // Alpha
        }
    };

Solution

  • My approach is little bit different from the reply you reffered to, but it works pretty well.

    #include <wrl.h>  
    #include <robuffer.h>
    
    using namespace Windows::UI::Xaml::Media::Imaging;
    using namespace Windows::Storage::Streams;  
    using namespace Microsoft::WRL;  
    
    typedef uint8 byte;
    byte* GetPointerToPixelData(IBuffer^ pixelBuffer, unsigned int *length)  
    {  
        if (length != nullptr)  
        {  
            *length = pixelBuffer ->Length;  
        }  
        // Query the IBufferByteAccess interface.  
        ComPtr<IBufferByteAccess> bufferByteAccess;  
        reinterpret_cast<IInspectable*>(pixelBuffer)->QueryInterface(IID_PPV_ARGS(&bufferByteAccess));  
    
        // Retrieve the buffer data.  
        byte* pixels = nullptr;  
        bufferByteAccess->Buffer(&pixels);  
        return pixels;  
    }
    
    MainPage::MainPage()
    {
        InitializeComponent();
    
        auto bitmap = ref new WriteableBitmap(50, 50);
        image->Source = bitmap;
    
        unsigned int length;
        byte* sourcePixels = GetPointerToPixelData(bitmap->PixelBuffer, &length);  
        const unsigned int width = bitmap->PixelWidth;  
        const unsigned int height = bitmap->PixelHeight; 
    
        create_async([this, width, height, sourcePixels] {
            byte* temp = sourcePixels;  
    
            // generate RED - BLUE gradient
            for(unsigned int k = 0; k < height; k++) {
                for (unsigned int i = 0; i < (width * 4); i += 4) {
                    int pos = k * (width * 4) + (i);  
                    temp[pos] = (byte)(0xFF * k / (float)height);               // B
                    temp[pos + 1] = 0x0;                                        // G
                    temp[pos + 2] = 0xFF - (byte)(0xFF * k / (float)height);    // R
                    temp[pos + 3] = 0xFF;                                       // A
                }  
            }
        });
    }
    

    enter image description here