ImageUtilM.cs 9.8 KB
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TSA_V.Common;

namespace TSA_V.DeviceLibrary
{
    public class ImageUtilM
    {
        private static string defPath = @"D:\image\";


        public static bool canSavePic(string path = "", int checkZhao = 50)
        {
            try
            {
                if (path == "")
                {
                    path = defPath;
                }
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string volume = path.Substring(0, path.IndexOf(':'));
                long freespace = GetHardDiskSpace(volume);
                int zhao = (int)(freespace / 1024);
                if (zhao < checkZhao)
                {
                    LogUtil.error(volume + "盘剩余空间:" + zhao + "G, 不再保存图片");
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogUtil.error($"canSavePic {path}  error :" + ex.ToString());
                return false;
            }
            return true;
        }
        private static long GetHardDiskSpace(string str_HardDiskName)
        {
            long totalSize = 0;
            str_HardDiskName = str_HardDiskName + ":\\";
            System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
            foreach (System.IO.DriveInfo drive in drives)
            {
                if (drive.Name == str_HardDiskName)
                {
                    totalSize = drive.TotalFreeSpace / (1024 * 1024);
                }
            }
            return totalSize;
        }
        public static bool AutoDelFiles(string path, int maxDay = 5, int minDay = 2)
        {
            if (Directory.Exists(path).Equals(false))
            {
                Directory.CreateDirectory(path);
            }

            for (int day = maxDay; day >= minDay; day--)
            {
                if (!canSavePic(path))
                {
                    DeleteOldFiles(path, day);
                }
                else
                {
                    return true;
                }
            }
            return canSavePic();
        }
        private static void DeleteOldFiles(string path = "", int days = 7)
        {
            if (path == "")
            {
                path = defPath;
            }
            try
            {
                LogUtil.info($"DeleteOldFiles 开始删除文件夹[{path}][{days}]天前的文件");
                if (!Directory.Exists(path) || days < 1) return;

                var now = DateTime.Now;
                foreach (var f in Directory.GetFileSystemEntries(path).Where(f => File.Exists(f)))
                {
                    DateTime createTime = File.GetCreationTime(f);

                    var elapsedTicks = now.Ticks - createTime.Ticks;
                    var elapsedSpan = new TimeSpan(elapsedTicks);

                    if (elapsedSpan.TotalDays > days)
                    {
                        File.Delete(f);

                        LogUtil.info($"DeleteOldFiles 删除文件: {f} ,创建时间:{createTime.ToLongTimeString()}");
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.error($"DeleteOldFiles {path} {days} error :" + ex.ToString());
            }
        }
        public static string SaveImageToFile(string deviceName, string cameraName, Image bitmap)
        {
            string date = DateTime.Now.ToString("yy-MM-dd-HH-mm-ss-") + DateTime.Now.Millisecond;
            string dire = @"D:\image\" + deviceName.Trim().Replace('_', '-') + @"\" + cameraName.Trim().Replace('_', '-').Replace(':', '-') + @"\";
            string iamgeName = date + ".bmp";
            try
            {
                if (AutoDelFiles(dire))
                {
                    bitmap.Save(dire + iamgeName, ImageFormat.Bmp);
                    //bitmap.Dispose();
                    LogUtil.info(deviceName + "  【" + cameraName + "】 保存图片到【" + dire + iamgeName + "】成功");
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("保存" + deviceName + "  【" + cameraName + "】的图片到【" + dire + iamgeName + "】出错" + ex.ToString());
            }
            return dire + iamgeName;
        }


        public static string BitMapToBase64(Image bitmap, int width = 0, int height = 0, int quality = 100)
        {
            try
            {
                if (bitmap == null) return "";
                if (width == 0 || height == 0)
                {
                    width = bitmap.Width;
                    height = bitmap.Height;
                }
                using (MemoryStream ms = new MemoryStream())
                {
                    var tarbmp = ZoomImage(bitmap, height, width, quality);
                    tarbmp.Save(ms, ImageFormat.Jpeg);
                    byte[] bytes = ms.GetBuffer();
                    string base64 = Convert.ToBase64String(bytes);
                    // tarbmp.Save($".\\test_BitMapToBase64.bmp",ImageFormat.Jpeg);
                    //File.WriteAllText("E:\\Neotel\\Codes\\DLL\\IPCamera\\WindowsFormsApp1\\bin\\Debug\\test_BitMapToBase64.txt", base64);
                    //Base64ToBitmap(base64);
                    return base64;

                }
            }
            catch (Exception e)
            {
                LogUtil.error("BitMapToStream: "+ e.ToString());
            }
            return "";
        }

        private static Image ZoomImage(Image bitmap, int destHeight, int destWidth, int quality = 100)
        {
            try
            {
                System.Drawing.Image sourImage = bitmap;
                int width = 0, height = 0;
                //按比例缩放             
                int sourWidth = sourImage.Width;
                int sourHeight = sourImage.Height;
                if (sourHeight > destHeight || sourWidth > destWidth)
                {
                    if ((sourWidth * destHeight) > (sourHeight * destWidth))
                    {
                        width = destWidth;
                        height = (destWidth * sourHeight) / sourWidth;
                    }
                    else
                    {
                        height = destHeight;
                        width = (sourWidth * destHeight) / sourHeight;
                    }
                }
                else
                {
                    width = sourWidth;
                    height = sourHeight;
                }
                Bitmap destBitmap = new Bitmap(destWidth, destHeight);
                Graphics g = Graphics.FromImage(destBitmap);
                g.Clear(Color.Transparent);
                //设置画布的描绘质量           
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.DrawImage(sourImage, new Rectangle((destWidth - width) / 2, (destHeight - height) / 2, width, height), 0, 0, sourImage.Width, sourImage.Height, GraphicsUnit.Pixel);
                //g.DrawImage(sourImage, new Rectangle(0, 0, destWidth, destHeight), new Rectangle(0, 0, sourImage.Width, sourImage.Height), GraphicsUnit.Pixel);
                g.Dispose();
                //设置压缩质量       
                System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
                long[] qualitys = new long[1];
                qualitys[0] = quality;
                System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualitys);
                encoderParams.Param[0] = encoderParam;
                sourImage.Dispose();
                return destBitmap;
            }
            catch (Exception ex)
            {
                return bitmap;
            }
        }

        public  static Bitmap Base64StringToImage(string inputStr)
        {
            try
            {
                if (inputStr == "")
                {
                    return null;
                }
                byte[] arr = Convert.FromBase64String(inputStr);
                //using (MemoryStream ms = new MemoryStream(arr))
                {
                    MemoryStream ms = new MemoryStream(arr);
                    Bitmap bmp = new Bitmap(ms);
                    ms.Close();
                    return bmp;
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("Base64StringToImage 转换失败/nException:" + ex.ToString());
                return null;
            }
        }

        public static bool  Base64StringToFile(string inputStr,string filePath)
        {
            try
            {
                if (inputStr == "")
                {
                    return false ;
                }
               
                byte[] arr = Convert.FromBase64String(inputStr);
                using (MemoryStream ms = new MemoryStream(arr))
                { 
                    using (Image image = Image.FromStream(ms))
                    {
                        image.Save(filePath, ImageFormat.Bmp); // 可根据实际需要保存为不同格式的图片
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("Base64StringToImage 转换失败/nException:" + ex.ToString());
                return false ;
            }
        }
    }
}