Mega Code Archive

 
Categories / Delphi / Graphic
 

Inserting a bitmap into an extended RichEdit or RichTextBox control

Title: Inserting a bitmap into an extended RichEdit or RichTextBox control. Question: How do I insert a picture into an enhanced RichEdit control (i.e. RxRichEdit, RichEditEx, RichEdit98, and Microsoft RichTextBox control) without using the clipboard or OLE? Answer: After quite a bit of searching the net, I found that there was no easy way to insert an image into a RichEdit. Inserting a bitmap as an object worked well enough, but the user can still open it up and edit it, and the image had to be an existing file. Using the clipboard worked even better, but wiped out the previous contents. Since my project required that the image was both reasonably uneditable, and left the clipboard intact, I had to resort to editing the RTF. If you have Rxlib, or use the Microsoft RichTextBox control (comes with VB5+), this may be of some use to you. Please forgive the sloppiness. Any suggestions on how to optimize it would be greatly appreciated, since loading larger images causes a delay I would rather do without. function BitmapToRTF(pict: TBitmap): string; var bi,bb,rtf: string; bis,bbs: Cardinal; achar: ShortString; hexpict: string; I: Integer; begin GetDIBSizes(pict.Handle,bis,bbs); SetLength(bi,bis); SetLength(bb,bbs); GetDIB(pict.Handle,pict.Palette,PChar(bi)^,PChar(bb)^); rtf := '{\rtf1 {\pict\dibitmap '; SetLength(hexpict,(Length(bb) + Length(bi)) * 2); I := 2; for bis := 1 to Length(bi) do begin achar := Format('%x',[Integer(bi[bis])]); if Length(achar) = 1 then achar := '0' + achar; hexpict[I-1] := achar[1]; hexpict[I] := achar[2]; Inc(I,2); end; for bbs := 1 to Length(bb) do begin achar := Format('%x',[Integer(bb[bbs])]); if Length(achar) = 1 then achar := '0' + achar; hexpict[I-1] := achar[1]; hexpict[I] := achar[2]; Inc(I,2); end; rtf := rtf + hexpict + ' }}'; Result := rtf; end; This function returns a snippet of RTF code that can be streamed into an RxRichEdit or RichTextBox selection. This seems to work well for me: {assume SS is a TStringStream, RE is a TRxRichEdit and BMP is a TBitmap containing a picture.} SS := TStringStream.Create(BitmapToRTF(BMP)); RE.PlainText := False; RE.StreamMode := [smSelection]; RE.Lines.LoadFromStream(SS); SS.Free; If you don't know what RxRichEdit is, and want to know, you can get it here: http://www.rxlib.com/ If you don't know what RTF (RichText Format) is, you can read a little about it here: http://chesworth.com/pv/file_format/rtf.txt {Edit: New version of the function seems to run alot faster.}