Delphi 2010 - decoding a Base64 encoded image from an XML document

I am trying to decode a base64 encoded EMF image from an XML document in my application and display it on the screen, however it never appears.

If I copy / paste data from an XML document into Notepad ++ and use a parameter Base64 Decodeand save the file as .emfit opens perfectly in mspaint. So I think the problem is how I decode it.

I tried the following decoding methods described in these articles:

How to encode / decode Base 64 string
http://www.swissdelphicenter.ch/torry/showcode.php?id=1223

I also tried the class to TIdDecoderMIMEno avail.

Does anyone know the most reliable way to decode base64 string encoding from XML?

Example

procedure TXmlSerializer.SaveImageFromString(const AValue: string);
var
  StrStream: TStringStream;
  Decoder: TIdDecoderMIME;
begin
  // AValue is base64 encoded string from XML doc
  Decoder := TIdDecoderMIME.Create(nil);
  try
    StrStream := TStringStream.Create(Decoder.DecodeString(AValue));
    try
      StrStream.SaveToFile('MyPath\Image.emf');
    finally
      StrStream.Free;
    end;
  finally
    Decoder.Free;
  end;
end;

Why does this not work above, but copying raw data into Notepad ++ and decoding and saving while working .emf?

+3
source share
3 answers

You use a string to store binary data; The Unicode version of Delphi 2010 may be "to blame" here.

Try using a base64 decoder that supports stream decoding and decodes directly to TFileStream; I use JclMime(part of the Jedi JCL), but I would be surprised if there weren’t an Indy MIME method that works with streams instead of strings.

JclMime , base64 XML:

procedure MimeDecode(const inputString: string; const outputStream: Tstream);
var
  ss: TStringStream;
begin
  ss := TStringStream.Create(inputString);
  try
    JclMime.MimeDecodeStream(ss, outputStream);
  finally
    ss.free;
  end;
end;
+6

TIdDecoderMIME . . , Indy.

OmniXML OmniXMLUtils.pas XML. / Base64. , .

TIdDecoderMIME. .

EDIT:

, . Base64 ( ASCII) , 2- . Base64 , , .

TStringStream AnsiStrings . , / .

SimpleStorage, . XML , :

  Jpeg := TJPEGImage.Create;
  try
    Jpeg.LoadFromStream(SrcStorage.Get('Image').Filter('gzip').AsBinary.Stream);
  finally
    Jpeg.Free;
  end;

( ).:)

+2

, , XML.

0 .

StrStream.Seek(0, soFromBeginning);

SaveToFile() TStringStream. ?

Also, since Delphi 2010 supports unicode strings, you can use AnsiStrings when processing binary data. Be careful when mixing multi-byte characters with single byte data.

0
source

Source: https://habr.com/ru/post/1741263/


All Articles