using AnQing.View; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Configuration; using System.Data; using System.Drawing; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Media.Imaging; using System.Windows; using System.Drawing.Imaging; using System.IO; using System.ComponentModel; using AnQing.Models; using OfficeOpenXml; using Newtonsoft.Json.Linq; namespace AnQing.Commons { public class Common { public static MainWindow main; /// /// 查询页面 /// public static History historycontrol; /// /// 设置页面 /// public static SetUpView setupview; public static string ConnectionString { get { var conn = ConfigurationManager.ConnectionStrings["ConnectionString"]; if (conn == null) { throw new Exception("未找到数据库连接字符串,请检查 App.config 是否正确!"); } return conn.ConnectionString; } } /// /// DataView 转 ObservableCollection /// public static ObservableCollection ConvertDataViewToObservableCollection(DataView view) where T : class, new() { ObservableCollection collection = new ObservableCollection(); if (view == null || view.Count == 0) { return collection; // 返回空集合 } // 获取 DataTable 结构(从 DataView 取出) DataTable table = view.Table; // 缓存属性信息 PropertyInfo[] properties = typeof(T).GetProperties(); foreach (DataRowView rowView in view) { DataRow row = rowView.Row; T obj = new T(); foreach (PropertyInfo info in properties) { if (table.Columns.Contains(info.Name)) { if (row[info.Name] != DBNull.Value) { // 获取属性类型 Type propertyType = info.PropertyType; // 获取DataRow中的值 object value = row[info.Name]; // 进行类型转换 if (propertyType.IsEnum) { value = Enum.ToObject(propertyType, value); } else if (propertyType == typeof(int) && value is long) { value = Convert.ToInt32(value); } else if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { if (value != null) { propertyType = Nullable.GetUnderlyingType(propertyType); value = Convert.ChangeType(value, propertyType); } } else { value = Convert.ChangeType(value, propertyType); } // 设置属性值 info.SetValue(obj, value, null); } } } collection.Add(obj); } return collection; } public static void MenuViewQuit() { main.MenuView.Children.Clear(); main.MenuView.Visibility = System.Windows.Visibility.Collapsed; } public static void SaveImage(Bitmap bitmap) { try { string directory = @"E:\Images"; if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } string filePath = Path.Combine(directory, $"Image_{DateTime.Now:yyyyMMdd_HHmmss}.bmp"); bitmap.Save(filePath, ImageFormat.Bmp); // 直接保存 BMP,避免二次转换 } catch (Exception e) { MessageBox.Show($"保存图片失败: {e.Message}"); } } public static BitmapSource BitmapToBitmapSource2(Bitmap bitmap) { IntPtr hBitmap = IntPtr.Zero; BitmapSource bitmapSource = null; try { // 使用 GetThumbnailImage 进行快速缩放 using (Bitmap resizedBitmap = (Bitmap)bitmap.GetThumbnailImage(760, 600, null, IntPtr.Zero)) { hBitmap = resizedBitmap.GetHbitmap(); bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); bitmapSource.Freeze(); // 让 BitmapSource 可跨线程使用 } } finally { if (hBitmap != IntPtr.Zero) { DeleteObject(hBitmap); // 避免 GDI 资源泄漏 } } return bitmapSource; } public static BitmapSource BitmapToBitmapSource(Bitmap bitmap) { IntPtr hBitmap = IntPtr.Zero; BitmapSource bitmapSource = null; try { hBitmap = bitmap.GetHbitmap(); bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } finally { if (hBitmap != IntPtr.Zero) { DeleteObject(hBitmap); // 避免 GDI 资源泄漏 } } return bitmapSource; } [System.Runtime.InteropServices.DllImport("gdi32.dll")] private static extern bool DeleteObject(IntPtr hObject); /// /// 保存ObservableCollection数据为excel /// /// /// public static void SaveToExcel(ObservableCollection tagInfos, string filePath) { ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial; using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("历史报废数据"); // 添加标题行 worksheet.Cells[1, 1].Value = "时间"; worksheet.Cells[1, 2].Value = "资产编号"; worksheet.Cells[1, 3].Value = "报废前图片路径"; worksheet.Cells[1, 4].Value = "报废后图片路径"; // 设置第一列(时间列)为文本格式,防止Excel自动转换日期 worksheet.Column(1).Style.Numberformat.Format = "@"; worksheet.Column(2).Style.Numberformat.Format = "@"; worksheet.Column(3).Style.Numberformat.Format = "@"; worksheet.Column(4).Style.Numberformat.Format = "@"; // 添加数据行 for (int i = 0; i < tagInfos.Count; i++) { worksheet.Cells[i + 2, 1].Value = tagInfos[i].time.ToString("yyyy-MM-dd HH:mm:ss"); // 添加单引号,强制 Excel 识别为文本 worksheet.Cells[i + 2, 2].Value = tagInfos[i].goodcode; worksheet.Cells[i + 2, 3].Value = tagInfos[i].img; worksheet.Cells[i + 2, 4].Value = tagInfos[i].img_after; } // 保存到文件 var fileInfo = new FileInfo(filePath); package.SaveAs(fileInfo); System.Windows.MessageBox.Show("数据导出成功!"); } } public static void EnsureFolderExists(string folderName) { string projectRoot = AppDomain.CurrentDomain.BaseDirectory; string folderPath = Path.Combine(projectRoot, folderName); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } else { string todayFolderName = DateTime.Now.ToString("yyyy-MM-dd"); string todayFolderPath = Path.Combine(folderPath, todayFolderName); // 如果今天日期的文件夹不存在,则创建 if (!Directory.Exists(todayFolderPath)) { Directory.CreateDirectory(todayFolderPath); } } } private static string configPath = "config.json"; public static string GetSetting(string key) { var json = JObject.Parse(File.ReadAllText(configPath)); return json["Settings"]?[key]?.ToString(); } public static void SetSetting(string key, string value) { var json = JObject.Parse(File.ReadAllText(configPath)); json["Settings"][key] = value; File.WriteAllText(configPath, json.ToString()); } } }