Which bytes should be edited in a WMF hex string stored in an RTF file in order to change image dimensions? RRS feed

  • Question

  • I  would like to save the WMF file with proper dimensions as they are in the editor (my saved WMFs have the dimensions of my screen resolution).  They come from a RichEdit.



    My goal is to convert the images that appear on a RichEdit to another format.

    Here is the fragment of the RTF:


    For each 2 chars in this string I converted it to hex and saved it through a memory stream. Then I opened it in Paint or GIMP and there is the image.  I even can convert it to a PNG file through ImageMagick tool. But the dimensions are wrong. How to fix this?

    I am using Lazarus.

    I could guess that the header is not OK, but how they can be opened by Paint and converted? So I guess the dimensions info is wrong in the header. In GIMP even the dimensions are right, here a link to the GIMP's dialogbox confirmation with the dimensions it has encountered in the file (  ).

    So the info is there, but is wrong. When I open the images in Paint, they are wrong. Microsoft Office Picture Manager can also open them correctly, but could not convert them so. I need to do it programmatically. TMetafile Delphi class could not open these files as well in order to be converted. So I could only edit the bytes.

    My RichEdit WMF data can not be accepted by ComputeAldusChecksum routine nor get a handle from SetWinMetaFileBits API call, which would convert it to an EMF format.
    procedure TMetafile.ReadWMFStream(Stream: TStream; Length: Longint);
    WMF: TMetafileHeader;
    BitMem: Pointer;
    MFP: TMetaFilePict;
    Stream.Read(WMF, SizeOf(WMF));
    if (WMF.Key <> WMFKEY) or (ComputeAldusChecksum(WMF) <> WMF.CheckSum) then
    raise EComponentError.Create('Invalid metafile.'); // <<<<<<<<<<<<<<< exception here
    Dec(Length, SizeOf(WMF));
    GetMem(Bitmem, Length);
    with FImage do
    Stream.Read(BitMem^, Length);
    FImage.FInch := WMF.Inch;
    if WMF.Inch = 0 then
    WMF.Inch := 96;
    FWidth := MulDiv(WMF.Box.Right - WMF.Box.Left,25400,WMF.Inch);
    FHeight := MulDiv(WMF.Box.Bottom - WMF.Box.Top,25400,WMF.Inch);
    with MFP do
    xExt := 0;
    yExt := 0;
    hmf := 0;
    FHandle := SetWinMetaFileBits(Length, BitMem, 0, MFP); 
    if FHandle = 0 then
    raise EComponentError.Create('Invalid metafile.'); // <<<<<<<<<<<<<< exception here
    Enhanced := False;
    Freemem(BitMem, Length);

    Thursday, December 4, 2014 7:24 PM