SoFunction
Updated on 2025-03-07

Share pictures and string conversion classes implemented by C#

In C#, Image provides abstract base class with functions for classes derived from Bitmap and Metafile, which means it is more general. When we use ("xxx"), we create a derived class entity of Image, so I use Image as a parameter, not Bitmap or something like that.

The picture is in the middle of the string conversion with the help of MemorySteam and Byte arrays. Below is the FormatChange class I wrote, which converts the two into each other. Of course, this also includes the mutual conversion between the picture and the Byte[] array.

class FormatChange
  {
    public static string ChangeImageToString(Image image)
    {
      try
      {
        MemoryStream ms = new MemoryStream();
        (ms, );
        byte[] arr = new byte[];
         = 0;
        (arr, 0, (int));
        ();
        string pic = Convert.ToBase64String(arr);

        return pic;
      }
      catch (Exception)
      {
        return "Fail to change bitmap to string!";
      }
    }

    public static Image ChangeStringToImage(string pic)
    {
      try
      {
        byte[] imageBytes = Convert.FromBase64String(pic);
        //Read in MemoryStream object        MemoryStream memoryStream = new MemoryStream(imageBytes, 0, );
        (imageBytes, 0, );
        //Convert to picture        Image image = (memoryStream);

        return image;
      }
      catch (Exception)
      {
        Image image = null;
        return image;
      }
    }
  }