0

I'm trying to write matImage

cv::Mat matImage;
matImage.create(480, 640, CV_8U);

to a bmp-file (for example "test.bmp") through Serialize(CArchive& ar) in the MFC application.

This code doesn't work

void CApplDoc::Serialize(CArchive& ar)
{
    if (ar.IsStoring())
    {
        // TODO: add storing code here
        CFile* file = ar.GetFile();
        CString strFileName = file->GetFileName();

        CStringA strFileNameA(strFileName);

        cv::imwrite(strFileNameA.GetBuffer(), matImage);
    }
}

How to do this correctly?

UPDATE

This code is not good enough, but it works

void CApplDoc::Serialize(CArchive& ar)
{
    CFile* file = ar.GetFile();
    CString strFileName = file->GetFileName();
    CStringA strFileNameA(strFileName);

    if (ar.IsStoring())
    {
        std::vector<uchar> buff;
        cv::imencode(".bmp", matImage, buff);
        ar.Write(&buff[0], buff.size());
        buff.empty();
    }
    else
    {
        UINT size = (UINT)file->GetLength();
        std::vector<uchar> buff;
        buff.resize(size);
        ar.Read(&buff[0], size);
        matImage = cv::imdecode(buff, CV_LOAD_IMAGE_GRAYSCALE);
        buff.empty();
    }
}
Vic.S
  • 23
  • 6
  • Why isn't that good enough? It seems it's not writing the bitmap header in to file, so it won't work with standard bitmap viewer. Otherwise it should work for your program. – Barmak Shemirani Dec 06 '15 at 17:31
  • I've checked it is writing the bitmap header into a file and images are opened by the standard windows image viewer. But I don't like this code anyway, it looks unsafe. – Vic.S Dec 07 '15 at 18:21
  • Why are you using MFC serialization and then throw it all out, reopen the same file that serves as a backing store for the `CArchive`, and write unstructured binary data to it? If you don't need MFC serialization, don't use MFC serialization. – IInspectable Dec 07 '15 at 19:55
  • I don't want. I'd like to use cv::imread and cv::imwrite, but MFC gives only CArchive (from Serialize function) or I shoud override 'OnFileOpen', write own CFileDialog, GetPathName() and so on. – Vic.S Dec 07 '15 at 20:14
  • You can just as well override [CDocument::OnOpenDocument](https://msdn.microsoft.com/en-us/library/ebc8c52a.aspx) and [CDocument::OnSaveDocument](https://msdn.microsoft.com/en-us/library/sd83ta1b.aspx). Overriding [CWinApp::OnFileOpen](https://msdn.microsoft.com/en-us/library/zwk0509s.aspx) is not a bad idea either, since your application can consume multiple file formats, and an appropriate file filter can only be set when instantiating your custom CFileDialog object. – IInspectable Dec 07 '15 at 21:10
  • That's what I looking for. Thank you! – Vic.S Dec 07 '15 at 21:28

0 Answers0