using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;

namespace Nirvana.Common
{
    public class ImageUtil
    {
        /// <summary>
        /// 图片转BASE64编码
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        public static string ImgToBase64String(Bitmap bmp)
        {
            MemoryStream ms = new MemoryStream();
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] arr = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(arr, 0, (int)ms.Length);
            ms.Close();
            String strbaser64 = Convert.ToBase64String(arr);
            return strbaser64;
        }
        /// <summary>
        /// 图片转BASE64编码
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string ImgToBase64String(string path)
        {
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            byte[] byteData = new byte[fs.Length];
            fs.Read(byteData, 0, byteData.Length);
            fs.Close();
            string data = Convert.ToBase64String(byteData);
            return data;
        }

        /// <summary>
        /// Base64转图片
        /// </summary>
        /// <param name="base64Img">Base64编码</param>
        /// <returns></returns>
        public static Bitmap Base64StringToImage(string base64Img)
        {
            byte[] bytes = Convert.FromBase64String(base64Img);
            MemoryStream ms = new MemoryStream();
            ms.Write(bytes, 0, bytes.Length);
            Bitmap bmp = new Bitmap(ms);
            return bmp;
        }
    }
}
