title: Convert Base64 String To Image Attachment
body: <p>I have an image converted to a base64 string that I need to convert back to an image and attach to a <code>MailMessage</code>.</p>
  
  <p>Here is the relevant code converting it from base64 string to image (I think I can skip the Image object and do this using one memory stream, but had some issues implementing that). Attempting to save the <code>Image</code> to a <code>MemoryStream</code> throws a generic GDI+ error:</p>
  
  <pre><code>Image image = ImageHelper.Base64ToImage(attachment.FieldData);
  
  if (image != null)
  {
      using (var ms = new MemoryStream())
      {
          image.Save(ms, ImageFormat.Png); // Throws a generic GDI+ error on Save
  
          ms.Position = 0;
  
          var imageAttachment = new Attachment(ms, "image.png", "image/png");
  
          message.Attachments.Add(imageAttachment);
      }
  }
  
  public static class ImageHelper
  {
      public static Image Base64ToImage(string base64String)
      {
          if (string.IsNullOrEmpty(base64String))
          {
              return null;
          }
  
          byte[] imageBytes = Convert.FromBase64String(base64String);
  
          using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
          {
              ms.Write(imageBytes, 0, imageBytes.Length);
  
              Image image = Image.FromStream(ms, true);
  
              return image;
          }
      }
  }
  </code></pre>
  
  <p>I'm able to serve up the raw base64 string elsewhere using an img tag and it works fine so I'm confident that the problem isn't with the base64 string itself:</p>
  
  <pre><code>&lt;img src="data:image/png;base64,&lt;myBase64StringHere&gt;" alt="My Image" width="500" /&gt;
  </code></pre>
  
  <p>I must be doing something wrong in converting it back, but I haven't been able to figure out the issue. Thanks for any help with this!</p>