Taking a JPEG-encoded screenshot to a buffer using GDI+ and C++

后端 未结 1 1096
余生分开走
余生分开走 2020-12-29 14:49

I\'ve adapted this code from another article here on SO. It takes a screenshot of the desktop and writes it to a file named \"test.jpg.\"

I\'m interested in saving t

相关标签:
1条回答
  • 2020-12-29 15:36

    Short answer: Use the IStream version of Gdiplus::Image::Save. Use CreateHStreamOnGlobal to make a temporary IStream that you can convert back to a buffer;

    Long winded version with code sample.

    Replace this line:

     iRes = (pScreenShot->Save(lpszFilename, &imageCLSID, &encoderParams) == Ok);
    

    With this block of code:

    // Note: For the sake of brevity and readability, I'm deliberately not checking
    // the return value of any of these calls. In production code, you should do diligent error 
    // checking on each function call. Also, there may be an optimization where you can just
    // use the memory of the stream itself (by calling GetHGlobalFromStream and GlobalLock)
    // But that's an exercise left to the reader.
    
    {
        IStream *pStream = NULL;
        LARGE_INTEGER liZero = {};
        ULARGE_INTEGER pos = {};
        STATSTG stg = {};
        ULONG bytesRead=0;
        HRESULT hrRet=S_OK;
    
        BYTE* buffer = NULL;  // this is your buffer that will hold the jpeg bytes
        DWORD dwBufferSize = 0;  // this is the size of that buffer;
    
    
        hrRet = CreateStreamOnHGlobal(NULL, TRUE, &pStream))
        hrRet = pScreenShot->Save(pStream, &imageCLSID, &encoderParams) == 0 ? S_OK : E_FAIL;
        hrRet = pStream->Seek(liZero, STREAM_SEEK_SET, &pos);
        hrRet = pStream->Stat(&stg, STATFLAG_NONAME);
    
        // allocate a byte buffer big enough to hold the jpeg stream in memory
        buffer = new BYTE[stg.cbSize.LowPart];
        hrRet = (buffer == NULL) ? E_OUTOFMEMORY : S_OK;
        dwBufferSize = stg.cbSize.LowPart;
    
        // copy the stream into memory
        hrRet = pStream->Read(buffer, stg.cbSize.LowPart, &bytesRead);
    
        // now go save "buffer" and "dwBufferSize" off somewhere.  This is the jpeg buffer
        // don't forget to free it when you are done
    
        // After success or if any of the above calls fail, don't forget to release the stream
        if (pStream)
        {
            pStream->Release();
        }
    }
    
    0 讨论(0)
提交回复
热议问题