Programming C++Builder project testjpg.exe raised exception class EJPEG with message 'JPEG error # 52'

When read the the Image field data from a table, program raise an exception as following:
"project abc.exe raised exception class EJPEG with message 'JPEG error # 52'".

This is caused by a bad jpeg format. A jpeg format use 2 position to verify the format.
The first two bytes and the last two bytes are 0xD8FF and 0xD9FF. In Delphi or cpp-builder, an TJPEG class use these 2 word to check if a jpeg file is correct. If it not meet, an error of "JPEG error #52" would raise.

To avoid a JPEG Error # 52, you should verify first two bytes of JPEG are 0xFFD8 (In delphi $D8FF), and verify last two bytes

of JPEG are 0xFFD9 (In Delphi $D9FF). This is an function written in cpp-builder, see below:
bool __fastcall IsValidJpeg(TStream* jpegStream)
    WORD w1, w2;
    jpegStream->Seek(0, soFromBeginning);
    jpegStream->Read(&w1, 2);
    jpegStream->Position = jpegStream->Size - 2;
    jpegStream->Read(&w2, 2);

    return (w1 == 0xD8FF) && (w2 == 0xD9FF);

//To call the function
void __fastcall TForm1::Button1Click(TObject *Sender)
    TOpenDialog *pDlg = new TOpenDialog(this);
    if (pDlg->Execute())
        TFileStream *streamFile = new TFileStream(pDlg->FileName, fmOpenRead);
            if (IsValidJpeg(streamFile))
                ShowMessage("Jpeg Image is OK.");
                ShowMessage("Bad Jpeg Image.");
            delete streamFile;
This codes has passed testing under Win2000+cpp-builder 6.

Add comment

Security code

Programming - C++Builder