title: Convert a raw RGB byte array to a JPG encoded string base64
body: <p>I am successfully converting a JPG image file into a base64 string, and then that string into a JPG image again.</p>
  
  <pre><code>string str64 = ImageToStrBase64(My.Resources.ImageJpg);
  PictureBox1.Image = Base64StrToImage(str64);
  </code></pre>
  
  <p><code>ImageToStrBase64()</code> and <code>Base64StrToImage()</code> are custom functions just to explain the idea, but I can place the code if necessary.</p>
  
  <p>I am also converting a raw byte array (RGB or BGR, no matters) into a base64.</p>
  
  <p>However, I do now need to convert a raw byte array into a JPG encoded base64 string. I am finding solutions that involves only an image file saving, but file management it's high time consuming. How to encode then a BGR byte array into a JPG byte array using, for example a memory stream?</p>
  
  <p>Function use to convert jpg into a formatted byte array:</p>
  
  <pre><code>public static string ImagetoStrBase64(System.Drawing.Image imageToEncode)
  {
      string base64String = "";
  
      using (System.Drawing.Image image = imageToEncode)
      {
          using (MemoryStream m = new MemoryStream())
          {
              image.Save(m, image.RawFormat);
              byte[] imageBytes = m.ToArray();
              base64String = Convert.ToBase64String(imageBytes);
          }
      }
  
      return base64String;
  }
  </code></pre>
  
  <hr>
  
  <p><strong>Update (regarding to <a href="https://chat.stackoverflow.com/transcript/message/48528759#48528759">chat</a>)</strong></p>
  
  <p>Let's simplify it... We have a <code>byte[]</code> with single green pixel: </p>
  
  <pre><code>byte[] rawPixelArray = new byte[] {0, 255, 0}; 
  </code></pre>
  
  <p>Then, <code>GetJpgBytes(rawPixelArray)</code> must return an encoded <code>byte[]</code> for a Jpeg image of 1x1 pixel. This is more clear I guess :)</p>