Search code examples
databasedelphiimagedelphi-2010delphi-2006

Getting Jpeg error #51 when loading from BLOB with Delphi 2010, fine w Delphi 2006


I have an old application developed in Delphi 2006 that I now needed to make some changes in.

In this app, I'm loading images from a MsSQL "image" field but when i compile with delphi 2010 I get the error : "raised exception class EJPEG with message 'JPEG error #51'."

The code that get's the image from the database:

aStream := TMemoryStream.Create;
Try
If LoadFromBlob(FieldByName('Picture'), aStream) then
begin
    Pic:=TJpegImage.Create;

    try
        Try
            Pic.LoadFromStream(aStream);
            Picture.Assign(Pic); // <------ JPEG Error #51 here w D2010
        Except
            //something went wrong loading
            HandleImageError();    
        End;

    finally
     Pic.Free;
    end;

end;
Finally
    aStream.Free;
End;

// ............

function LoadFromBlob(const AField: TField; const Stream: TStream): boolean;
var
    ResultStr: string;
    PResultStr: PChar;
begin
    Result := false;
    if (Assigned(AField)) and (Assigned(Stream)) then begin
        try
            ResultStr := AField.Value;
            If ResultStr <> '' then
            begin
                PResultStr := PChar(ResultStr);
                Stream.Write(PResultStr^, Length(ResultStr));
                Stream.Seek(0,0);
                Result := true;
            end;
        except
        end;
    end;
end;

Googled around a bit and found out that error #51 means: JERR_NO_QUANT_TABLE, whatever that means.

When I compile with Delphi 2006, the same code works fine with no errors, so what's going wrong with D2010?


Solution

  • In D2010 Char changed from Ansi to Unicode, which means it occupies two bytes instead of one. Change your variables in LoadFromBlob to AnsiString and PAnsiChar and it should work.

    Update: Instead of Field.Value (Variant) you should better access Field.AsAnsiString; The variant access might include an implicit Unicode->Ansi conversion which introduces the error.