C realization of pictures string mutual conversion class sharing

  • 2021-01-19 22:21:40
  • OfStack

In C#, Image is an abstract base class that provides functionality for classes derived from Bitmap and Metafile. That is to say, it is more generic. When we use Image.FromFile("xxx"), we create an entity derived from Image, so I use Image as an argument, not something like Bitmap.

The image is an string conversion with the help of MemorySteam and Byte arrays. Here is the FormatChange class I wrote, where the two conversion processes are interconverted. Of course, this also includes images and Byte[] array conversion.


class FormatChange
  {
    public static string ChangeImageToString(Image image)
    {
      try
      {
        MemoryStream ms = new MemoryStream();
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
        byte[] arr = new byte[ms.Length];
        ms.Position = 0;
        ms.Read(arr, 0, (int)ms.Length);
        ms.Close();
        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.Length);
        memoryStream.Write(imageBytes, 0, imageBytes.Length);
        // Into a picture 
        Image image = Image.FromStream(memoryStream);

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


Related articles: