How can I take a screenshot and save it as JPEG on Windows?

前端 未结 11 1803
暖寄归人
暖寄归人 2020-12-02 15:11

I\'m trying to find a (somewhat) easy way to take a screenshot on window and save the resulting HBITMAP as a JPEG. The tricky part here is that since the code is in C I can\

11条回答
  •  广开言路
    2020-12-02 15:27

    OK, after a lot of effort here's the answer:

    int SaveJpeg(HBITMAP hBmp, LPCWSTR lpszFilename, ULONG uQuality)
    {
        ULONG *pBitmap = NULL;
        CLSID imageCLSID;
        EncoderParameters encoderParams;
        int iRes = 0;
    
        typedef Status (WINAPI *pGdipCreateBitmapFromHBITMAP)(HBITMAP, HPALETTE, ULONG**);
        pGdipCreateBitmapFromHBITMAP lGdipCreateBitmapFromHBITMAP;
    
        typedef Status (WINAPI *pGdipSaveImageToFile)(ULONG *, const WCHAR*, const CLSID*, const EncoderParameters*);
        pGdipSaveImageToFile lGdipSaveImageToFile;
    
        // load GdipCreateBitmapFromHBITMAP
        lGdipCreateBitmapFromHBITMAP = (pGdipCreateBitmapFromHBITMAP)GetProcAddress(hModuleThread, "GdipCreateBitmapFromHBITMAP");
        if(lGdipCreateBitmapFromHBITMAP == NULL)
        {
            // error
            return 0;
        }
    
        // load GdipSaveImageToFile
        lGdipSaveImageToFile = (pGdipSaveImageToFile)GetProcAddress(hModuleThread, "GdipSaveImageToFile");
        if(lGdipSaveImageToFile == NULL)
        {
            // error
            return 0;
        }
    
            lGdipCreateBitmapFromHBITMAP(hBmp, NULL, &pBitmap);
    
           iRes = GetEncoderClsid(L"image/jpeg", &imageCLSID);
           if(iRes == -1)
        {
            // error
            return 0;
        }
        encoderParams.Count = 1;
        encoderParams.Parameter[0].NumberOfValues = 1;
        encoderParams.Parameter[0].Guid  = EncoderQuality;
        encoderParams.Parameter[0].Type  = EncoderParameterValueTypeLong;
        encoderParams.Parameter[0].Value = &uQuality;
    
        lGdipSaveImageToFile(pBitmap, lpszFilename, &imageCLSID, &encoderParams);
    
    
        return 1;
    }
    
    • what is hModuleThread? Look in here. You can replace with GetModuleHandle()

    • what is GetEncoderClsid? Look here.

    Now the question is, how do I save the encoded pBitmap (as a jpeg) into a BYTE buffer?

提交回复
热议问题