图片转为Base64编码的文本
作者:C/S框架网  发布日期:2017-10-21 15:37:42
  图片转为Base64编码的文本


C# Code:

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace CSFramework.WebApi.Core
{
   /// <summary>
   /// 图片转为Base64编码的文本
   /// </summary>
   public static class ImageStringConverter
   {
      /// <summary>
      /// 图片转为base64编码的文本
      /// </summary>
      /// <param name="imageFilePath">图片文件</param>
      /// <param name="format">压缩格式</param>
      /// <returns></returns>
      public static string ToBase64String(string imageFilePath, ImageFormat format)
      {
         try
         {
            Bitmap bmp = new Bitmap(imageFilePath);
            MemoryStream ms = new MemoryStream();
            bmp.Save(ms, format);
            byte[] arr = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(arr, 0, (int)ms.Length);
            ms.Close();
            ms.Dispose();
            bmp.Dispose();
            return Convert.ToBase64String(arr);
         }
         catch
         {
            return "";
         }
      }
      
      /// <summary>
      /// base64编码的文本转为图片
      /// </summary>
      /// <param name="imageBase64">base64编码的文本</param>
      /// <returns></returns>
      public static Image ToImage(string imageBase64)
      {
         try
         {
            byte[] imageBytes = Convert.FromBase64String(imageBase64);
            //读入MemoryStream对象
            MemoryStream memoryStream = new MemoryStream(imageBytes, 0, imageBytes.Length);
            memoryStream.Write(imageBytes, 0, imageBytes.Length);
            //转成图片
            Image image = Image.FromStream(memoryStream);
            return image;
         }
         catch
         {
            return null;
         }
      }
   }
}


//来源:C/S框架网(www.csframework.com) QQ:23404761



上一篇 下一篇