如何使用 Wincodec.h (WIC) 将图像写入 STDOUT

How to write an image to STDOUT with Wincodec.h (WIC)

我遇到了 并且无法弄清楚如何在 HRESULT SavePixelsToFile32bppPBGRA(UINT width, UINT height, UINT stride, LPBYTE pixels, LPWSTR filePath, const GUID &format) 函数内将 stream->InitializeFromFilename 更改为输出到 STDOUT 的内容。尝试使用 stream->InitializeFromMemory 但由于 C++ 经验很少而碰壁。

这背后的原因是我正在构建一些东西并且想使用其他东西来管道示例的标准输出。

提前问候

感谢@SimonMourier,我能够更新他的代码来实现所需要的。

SavePixelsToFile32bppPBGRA 现在将数据写入 IStream 指针 streamOut。它还在最后调用一个新函数来输出数据。

HRESULT SavePixelsToFile32bppPBGRA(UINT width, UINT height, UINT stride, LPBYTE pixels, const GUID& format)
{
    if (!pixels)
        return E_INVALIDARG;

    HRESULT hr = S_OK;
    IWICImagingFactory* factory = nullptr;
    IWICBitmapEncoder* encoder = nullptr;
    IWICBitmapFrameEncode* frame = nullptr;
    IWICStream* streamOut = nullptr;
    IStream * streamIn = nullptr;
    GUID pf = GUID_WICPixelFormat32bppPBGRA;
    BOOL coInit = CoInitialize(nullptr);

    HRCHECK(CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&factory)));
    HRCHECK(factory->CreateStream(&streamOut));
    HRCHECK(CreateStreamOnHGlobal(NULL, true, &streamIn));
    HRCHECK(streamOut->InitializeFromIStream(streamIn));
    HRCHECK(factory->CreateEncoder(format, nullptr, &encoder));
    HRCHECK(encoder->Initialize(streamOut, WICBitmapEncoderNoCache));
    HRCHECK(encoder->CreateNewFrame(&frame, nullptr)); // we don't use options here
    HRCHECK(frame->Initialize(nullptr)); // we dont' use any options here
    HRCHECK(frame->SetSize(width, height));
    HRCHECK(frame->SetPixelFormat(&pf));
    HRCHECK(frame->WritePixels(height, stride, stride * height, pixels));
    HRCHECK(frame->Commit());
    HRCHECK(encoder->Commit());

    sendIStreamToOutput(streamOut);

cleanup:
    RELEASE(streamIn);
    RELEASE(streamOut);
    RELEASE(frame);
    RELEASE(encoder);
    RELEASE(factory);
    if (coInit) CoUninitialize();
    return hr;
}

sendIStreamToOutput 从 IStream 中读取数据并将其写入 std::cout(二进制模式处于活动状态)。

void sendIStreamToOutput (IStream * pIStream) {

    STATSTG sts;
    pIStream->Stat(&sts, STATFLAG_DEFAULT);
    ULARGE_INTEGER uli = sts.cbSize;
    LARGE_INTEGER zero;
    zero.QuadPart = 0;
    ULONG size = (ULONG)uli.QuadPart;
    char* bits = new char[size];
    ULONG written;
    pIStream->Seek(zero, STREAM_SEEK_SET, NULL);
    pIStream->Read(bits, size, &written);
    
    std::ostream& lhs = std::cout;

    _setmode(_fileno(stdout), _O_BINARY);

    lhs.write(bits, size);

    fflush(stdout);

    delete[] bits;
 }