ImageUtilM.cs
9.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
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 ;
}
}
}
}