I am attempting to insert an image into a rich text file. I have read some of the answers already, but I’m not getting it quite right. The code I am using is as follows:
string[] imgfiles = Directory.GetFiles(dirin, "*.png");
foreach (string imageFileName in imgfiles)
{
var someImage = Image.FromFile(imageFileName);
MemoryStream memStream = new MemoryStream();
someImage.Save(memStream, ImageFormat.Png);
byte[] imgbytedata = memStream.ToArray();
memStream.Close();
memStream.Dispose();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < imgbytedata.Length; i++)
{
sb.Append(imgbytedata[i]);
}
var imgstr = "{" + string.Format("\\pict\\pngblip\\picw{0}\\pich{1}\\picwgoal{0}\\pichgoal{1}\\bin binary {2}", someImage.Width, someImage.Height, sb.ToString()) + "}";
sb = null;
rtb.AppendText(imgstr);
}
When you are building your string from the byte array, you are appending the string version of your byte data, i.e. “76”,”127″,”90″, etc.
One major problem (I don’t know if this is your actual problem) is that when you attempt to read it, the reader has no idea how to extract bytes from it. Take this example…
OUTPUT:
Solution: Convert your byte array into a base64String with
Convert.ToBase64Stringand store that in the file.Like so….
OUTPUT
Another potential problem: I’ve heard tell that using
string.Formatwith exceptionally large strings can cause problems. I can fathom a case in which you generate memory exceptions with large image files.Solution: Don’t use
string.Format. Either append your headers to theStringBuilderfirst OR write the header and image data in two separate actions.