using OpenCvSharp; using Resources; using SmartCoalApplication.Actions; using SmartCoalApplication.Annotation.Enum; using SmartCoalApplication.Annotation.Measure; using SmartCoalApplication.Base; using SmartCoalApplication.Base.CommTool; using SmartCoalApplication.Base.Enum; using SmartCoalApplication.Base.SettingModel; using SmartCoalApplication.Core; using SmartCoalApplication.Core.DbOpreate.DbModel; using SmartCoalApplication.Measure; using SmartCoalApplication.Resources; using SmartCoalApplication.SystemLayer; using SmartCoalApplication.SystemLayer.FileDlgExtenders.FileDialogExtenders; using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Reflection; using System.Runtime.Serialization; using System.Security; using System.Windows.Forms; namespace SmartCoalApplication { internal class DocumentWorkspace : DocumentView { /// /// 主控件 /// private AppWorkspace appWorkspace; /// /// 缩放模式 /// private ZoomBasis zoomBasis; /// /// 文件路径 /// private string filePath = null; /// /// 文件名 /// public string fileText = null; private ImageResource statusIcon = null; public ZipHandleHelper zipHandleHelper;//zip对象 public BatchSaveAutoModel batchSaveAutoModel; #region 底部按钮选中状态 /// /// 最佳 /// public bool best = false; /// /// 最大最小 /// public bool maxMin = false; /// /// 原始状态 /// public bool origin = true; /// /// 伽马0.45 /// public bool gamma45 = false; /// /// 移动模式 /// public bool mobileMode = false; /// /// 指针模式 /// public bool cursorMode = true; /// /// MainForm /// #endregion public ImageResource StatusIcon { get { return this.statusIcon; } } public string StatusText { get { if (!string.IsNullOrEmpty(filePath)) { try { FileInfo fi = new FileInfo(filePath); return fi.CreationTime + "、" + FileOperationHelper.GetLength(fi.Length) + "、" + this.appWorkspace.ActiveDocumentWorkspace.CompositionSurface.Width + "*" + this.appWorkspace.ActiveDocumentWorkspace.CompositionSurface.Height; } catch (Exception) { } } return ""; } } public event EventHandler StatusChanged; protected virtual void OnStatusChanged() { if (StatusChanged != null) { StatusChanged(this, EventArgs.Empty); } } protected override void OnSizeChanged(EventArgs e) { PerformLayout(); base.OnSizeChanged(e); } protected override void OnLayout(LayoutEventArgs e) { if (this.zoomBasis == ZoomBasis.FitToWindow) { ZoomToWindow(); // This bizarre ordering of setting PanelAutoScroll prevents some very weird layout/scroll-without-scrollbars stuff. PanelAutoScroll = true; PanelAutoScroll = false; } base.OnLayout(e); } protected override void OnResize(EventArgs e) { if (this.zoomBasis == ZoomBasis.FitToWindow) { PerformLayout(); } base.OnResize(e); } public DocumentWorkspace(AppWorkspace appWorkspace) { this.AppWorkspaceTop = appWorkspace; InitializeComponent(); this.InitToolsAndManager(); this.ShowContextMenuStrip1(); this.panel.MouseDown += new MouseEventHandler(this.ShowContextMenuStrip2); this.RulersEnabled = Settings.CurrentUser.GetBoolean(SettingNames.Rulers, true); this.zoomBasis = ZoomBasis.FitToWindow; } private void ShowContextMenuStrip2(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) this.ShowContextMenuStrip1(); } protected override void OnUnitsChanged() { base.OnUnitsChanged(); } private void InitializeComponent() { } protected override void Dispose(bool disposing) { base.Dispose(disposing); } public override void ZoomIn() { this.ZoomBasis = ZoomBasis.ScaleFactor; base.ZoomIn(); } public override void ZoomIn(double factor) { this.ZoomBasis = ZoomBasis.ScaleFactor; base.ZoomIn(factor); } public override void ZoomOut() { this.ZoomBasis = ZoomBasis.ScaleFactor; base.ZoomOut(); } public override void ZoomOut(double factor) { this.ZoomBasis = ZoomBasis.ScaleFactor; base.ZoomOut(factor); } public event EventHandler ZoomBasisChanging; protected virtual void OnZoomBasisChanging() { if (ZoomBasisChanging != null) { ZoomBasisChanging(this, EventArgs.Empty); } } public event EventHandler ZoomBasisChanged; protected virtual void OnZoomBasisChanged() { if (ZoomBasisChanged != null) { ZoomBasisChanged(this, EventArgs.Empty); } } public ZoomBasis ZoomBasis { get { return this.zoomBasis; } set { if (this.zoomBasis != value) { OnZoomBasisChanging(); this.zoomBasis = value; switch (this.zoomBasis) { //合适大小(完整显示图像) case ZoomBasis.FitToWindow: ZoomToWindow(); PanelAutoScroll = true; PanelAutoScroll = false; this.zoomBasis = ZoomBasis.FitToWindow; break; //实际大小 case ZoomBasis.ScaleFactor: PanelAutoScroll = true; break; //合适宽度 case ZoomBasis.FitToWidth: ZoomToWidth(); PanelAutoScroll = true; this.zoomBasis = ZoomBasis.FitToWidth; break; //合适高度 case ZoomBasis.FitToHeight: ZoomToHeight(); PanelAutoScroll = true; this.zoomBasis = ZoomBasis.FitToHeight; break; default: throw new InvalidEnumArgumentException(); } OnZoomBasisChanged(); } } } protected override void HandleMouseWheel(Control sender, MouseEventArgs e) { if (Control.ModifierKeys == Keys.Control) { double mouseDelta = (double)e.Delta / 120.0f; Rectangle visibleDocBoundsStart = this.VisibleDocumentBounds; System.Drawing.Point mouseDocPt = this.MouseToDocument(sender, new System.Drawing.Point(e.X, e.Y)); RectangleF visibleDocDocRect1 = this.VisibleDocumentRectangleF; PointF mouseNPt = new PointF( (mouseDocPt.X - visibleDocDocRect1.X) / visibleDocDocRect1.Width, (mouseDocPt.Y - visibleDocDocRect1.Y) / visibleDocDocRect1.Height); Rectangle rc = this.PanelClientRectangle; int width = this.SurfaceScrollableWidth; int height = this.SurfaceScrollableHeight; //获取鼠标在图像中的坐标定位 double originX = 0.5; double originY = 0.5; double ptxInDoc = mouseDocPt.X * this.ScaleRatio; double ptyInDoc = mouseDocPt.Y * this.ScaleRatio; if (rc.Width < width) { originX = (ptxInDoc + this.PanelScrollPosition.X - 150.0) / width; } if (rc.Height < height) { originY = (ptyInDoc + this.PanelScrollPosition.Y - 75.0) / height; } const double factor = 1.12; double mouseFactor = Math.Pow(factor, Math.Abs(mouseDelta)); if (e.Delta > 0) { this.ZoomIn(mouseFactor); } else if (e.Delta < 0) { this.ZoomOut(mouseFactor); } RectangleF visibleDocDocRect2 = this.VisibleDocumentRectangleF; PointF scrollPt2 = new PointF( mouseDocPt.X - visibleDocDocRect2.Width * mouseNPt.X, mouseDocPt.Y - visibleDocDocRect2.Height * mouseNPt.Y); this.DocumentScrollPositionF = scrollPt2; int width2 = this.SurfaceScrollableWidth; int height2 = this.SurfaceScrollableHeight; if ((rc.Width < width2 || rc.Height < height2) && (rc.Width < width || rc.Height < height)) { //根据鼠标在图像中的坐标重新定位放大后的图像 this.PanelScrollPosition = new System.Drawing.Point( (int)(width2 * originX - ptxInDoc + 150), (int)(height2 * originY - ptyInDoc + 75)); } else if (rc.Width < width2 || rc.Height < height2) { this.PanelScrollPosition = new System.Drawing.Point((int)(width2 - rc.Width) / 2 + 150, (int)(height2 - rc.Height) / 2 + 75); } else { this.PanelScrollPosition = new System.Drawing.Point((int)(width2 - rc.Width) / 2 + 0, (int)(height2 - rc.Height) / 2 + 0); } Rectangle visibleDocBoundsEnd = this.VisibleDocumentBounds; if (visibleDocBoundsEnd != visibleDocBoundsStart) { // Make sure the screen updates, otherwise it can get a little funky looking this.Update(); } } base.HandleMouseWheel(sender, e); } public void UpdateAuxiliaryLineEnabled() { } public void UpdateGridLineEnabled() { this.GridLineEnabled = this.GridLineEnabled; } protected override void OnLoad(EventArgs e) { if (this.appWorkspace == null) { throw new InvalidOperationException("Must set the Workspace property"); } base.OnLoad(e); } public event EventHandler ActiveLayerChanging; protected void OnLayerChanging() { if (ActiveLayerChanging != null) { ActiveLayerChanging(this, EventArgs.Empty); } } public event EventHandler ActiveLayerChanged; protected void OnLayerChanged() { this.Focus(); if (ActiveLayerChanged != null) { ActiveLayerChanged(this, EventArgs.Empty); } } public event EventHandler ToolChanging; protected void OnToolChanging() { if (ToolChanging != null) { ToolChanging(this, EventArgs.Empty); } } public event EventHandler ToolChanged; protected void OnToolChanged() { if (ToolChanged != null) { ToolChanged(this, EventArgs.Empty); } } public AppWorkspace AppWorkspace { get { return this.appWorkspace; } set { this.appWorkspace = value; } } public event EventHandler FilePathChanged; protected virtual void OnFilePathChanged() { if (FilePathChanged != null) { FilePathChanged(this, EventArgs.Empty); } } public string FilePath { get { return this.filePath; } } public string GetFriendlyName() { string friendlyName; if (this.filePath != null) { friendlyName = Path.GetFileName(this.filePath); } else if (this.fileText != null) { friendlyName = this.fileText; } else { friendlyName = PdnResources.GetString("Untitled.FriendlyName"); } return friendlyName; } public event EventHandler SaveOptionsChanged; protected virtual void OnSaveOptionsChanged() { if (SaveOptionsChanged != null) { SaveOptionsChanged(this, EventArgs.Empty); } } /// /// Sets the FileType and SaveConfigToken parameters that are used if the /// user chooses "Save" from the File menu. These are not used by the /// DocumentControl class and should be used by whoever actually goes /// to save the Document instance. /// /// /// public void SetDocumentSaveOptions(string newFilePath) { this.filePath = newFilePath; OnFilePathChanged(); OnSaveOptionsChanged(); } public void GetDocumentSaveOptions(out string filePathResult) { filePathResult = this.filePath; } private ZoomBasis savedZb; private ScaleFactor savedSf; protected override void OnDocumentChanging(Document newDocument) { base.OnDocumentChanging(newDocument); this.savedZb = this.ZoomBasis; this.savedSf = ScaleFactor; } protected override void OnDocumentChanged() { if (this.Document != null) { bool oldDirty = this.Document.Dirty; this.Document.Invalidate(); this.Document.Dirty = oldDirty; this.ZoomBasis = this.savedZb; if (this.savedZb == ZoomBasis.ScaleFactor) { ScaleFactor = this.savedSf; } } AutoScrollPosition = new System.Drawing.Point(0, 0); base.OnDocumentChanged(); } public void AddToMruList() { string fullFileName = Path.GetFullPath(this.FilePath); MostRecentFile mrf = new MostRecentFile(fullFileName, null); if (AppWorkspace.MostRecentFiles.Contains(fullFileName)) { AppWorkspace.MostRecentFiles.Remove(fullFileName); } AppWorkspace.MostRecentFiles.Add(mrf); AppWorkspace.MostRecentFiles.SaveMruList(); } public static DialogResult ShowFileDialog(Control owner, IFileDialog fd) { string initialDirectory = Settings.CurrentUser.GetString(SettingNames.LastFileDialogDirectory, fd.InitialDirectory); bool dirExists = false; try { DirectoryInfo dirInfo = new DirectoryInfo(initialDirectory); using (new WaitCursorChanger(owner)) { dirExists = dirInfo.Exists; if (!dirInfo.Exists) { initialDirectory = fd.InitialDirectory; } } } catch (Exception) { initialDirectory = fd.InitialDirectory; } fd.InitialDirectory = initialDirectory; OurFileDialogUICallbacks ouc = new OurFileDialogUICallbacks(); DialogResult result = fd.ShowDialog(owner, ouc); if (result == DialogResult.OK) { string fileName; if (fd is IFileOpenDialog) { string[] fileNames = ((IFileOpenDialog)fd).FileNames; if (fileNames.Length > 0) { fileName = fileNames[0]; } else { fileName = null; } } else if (fd is IFileSaveDialog) { fileName = ((IFileSaveDialog)fd).FileName; } else { throw new InvalidOperationException(); } if (fileName != null) { string newDir = Path.GetDirectoryName(fileName); Settings.CurrentUser.SetString(SettingNames.LastFileDialogDirectory, newDir); } else { throw new FileNotFoundException(); } } return result; } private sealed class OurFileDialogUICallbacks : IFileDialogUICallbacks { public FileOverwriteAction ShowOverwritePrompt(IWin32Window owner, string pathName) { FileOverwriteAction returnVal; string title = PdnResources.GetString("SaveAs.OverwriteConfirmation.Title"); string textFormat = PdnResources.GetString("SaveAs.OverwriteConfirmation.Text.Format"); string fileName; try { fileName = Path.GetFileName(pathName); } catch (Exception) { fileName = pathName; } string text = string.Format(textFormat, fileName); DialogResult result = MessageBox.Show(owner, text, title, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2); switch (result) { case DialogResult.Yes: returnVal = FileOverwriteAction.Overwrite; break; case DialogResult.No: returnVal = FileOverwriteAction.Cancel; break; default: throw new InvalidEnumArgumentException(); } return returnVal; } public bool ShowError(IWin32Window owner, string filePath, Exception ex) { if (ex is PathTooLongException) { string title = PdnInfo.GetBareProductName(); string message = PdnResources.GetString("FileDialog.PathTooLongException.Message"); MessageBox.Show(owner, message, title, MessageBoxButtons.OK, MessageBoxIcon.Error); return true; } else { return false; } } public IFileTransferProgressEvents CreateFileTransferProgressEvents() { return new OurProgressEvents(); } } private sealed class OurProgressEvents : IFileTransferProgressEvents { private TransferProgressDialog progressDialog; private ICancelable cancelSink; private int itemCount = 0; private int itemOrdinal = 0; private string itemName = string.Empty; private long totalWork; private long totalProgress; private const int maxPBValue = 200; // granularity of progress bar. 100 means 1%, 200 means 0.5%, etc. private bool cancelRequested = false; public OurProgressEvents() { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "cancelSink")] public void BeginOperation(IWin32Window owner, EventHandler callWhenUIShown, ICancelable cancelSink) { if (this.progressDialog != null) { throw new InvalidOperationException("Operation already in progress"); } this.progressDialog = new TransferProgressDialog(); this.progressDialog.Text = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.TransferProgress.Title"); this.progressDialog.Icon = Utility.ImageToIcon(PdnResources.GetImageResource("Icons.MenuFileOpenIcon.png").Reference); this.progressDialog.ProgressBar.Style = ProgressBarStyle.Marquee; this.progressDialog.ProgressBar.Maximum = maxPBValue; this.progressDialog.CancelClicked += delegate (object sender, EventArgs e) { this.cancelRequested = true; this.cancelSink.RequestCancel(); UpdateUI(); }; EventHandler progressDialog_Shown = delegate (object sender, EventArgs e) { callWhenUIShown(this, EventArgs.Empty); }; this.cancelSink = cancelSink; this.itemOrdinal = 0; this.cancelRequested = false; this.itemName = string.Empty; this.itemCount = 0; this.itemOrdinal = 0; this.totalProgress = 0; this.totalWork = 0; this.progressDialog.Shown += progressDialog_Shown; this.progressDialog.ShowDialog(owner); this.progressDialog.Shown -= progressDialog_Shown; this.progressDialog.Dispose(); this.progressDialog = null; this.cancelSink = null; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "itemCount")] public void SetItemCount(int itemCount) { if (this.progressDialog.InvokeRequired) { this.progressDialog.BeginInvoke(new Procedure(SetItemCount), new object[] { itemCount }); } else { this.itemCount = itemCount; UpdateUI(); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "itemOrdinal")] public void SetItemOrdinal(int itemOrdinal) { if (this.progressDialog.InvokeRequired) { this.progressDialog.BeginInvoke(new Procedure(SetItemOrdinal), new object[] { itemOrdinal }); } else { this.itemOrdinal = itemOrdinal; this.totalWork = 0; this.totalProgress = 0; UpdateUI(); } } public void SetItemInfo(string itemInfo) { if (this.progressDialog.InvokeRequired) { this.progressDialog.BeginInvoke(new Procedure(SetItemInfo), new object[] { itemInfo }); } else { this.itemName = itemInfo; UpdateUI(); } } public void BeginItem() { if (this.progressDialog.InvokeRequired) { this.progressDialog.BeginInvoke(new Procedure(BeginItem), null); } else { this.progressDialog.ProgressBar.Style = ProgressBarStyle.Continuous; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "totalWork")] public void SetItemWorkTotal(long totalWork) { if (this.progressDialog.InvokeRequired) { this.progressDialog.BeginInvoke(new Procedure(SetItemWorkTotal), new object[] { totalWork }); } else { this.totalWork = totalWork; UpdateUI(); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "totalProgress")] public void SetItemWorkProgress(long totalProgress) { if (this.progressDialog.InvokeRequired) { this.progressDialog.BeginInvoke(new Procedure(SetItemWorkProgress), new object[] { totalProgress }); } else { this.totalProgress = totalProgress; UpdateUI(); } } public void EndItem(WorkItemResult result) { if (this.progressDialog.InvokeRequired) { this.progressDialog.BeginInvoke(new Procedure(EndItem), new object[] { result }); } else { } } public void EndOperation(OperationResult result) { if (this.progressDialog.InvokeRequired) { this.progressDialog.BeginInvoke(new Procedure(EndOperation), new object[] { result }); } else { this.progressDialog.Close(); } } public WorkItemFailureAction ReportItemFailure(Exception ex) { if (this.progressDialog.InvokeRequired) { object result = this.progressDialog.Invoke( new Function(ReportItemFailure), new object[] { ex }); return (WorkItemFailureAction)result; } else { WorkItemFailureAction result; result = ShowFileTransferFailedDialog(ex); return result; } } private WorkItemFailureAction ShowFileTransferFailedDialog(Exception ex) { WorkItemFailureAction result; Icon formIcon = this.progressDialog.Icon; string formTitle = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ItemFailureDialog.Title"); Image taskImage = PdnResources.GetImageResource("Icons.WarningIcon.png").Reference; string introTextFormat = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ItemFailureDialog.IntroText.Format"); string introText = string.Format(introTextFormat, ex.Message); TaskButton retryTB = new TaskButton( PdnResources.GetImageResource("Icons.MenuImageRotate90CWIcon.png").Reference, PdnResources.GetString("DocumentWorkspace.ShowFileDialog.RetryTB.ActionText"), PdnResources.GetString("DocumentWorkspace.ShowFileDialog.RetryTB.ExplanationText")); TaskButton skipTB = new TaskButton( PdnResources.GetImageResource("Icons.HistoryFastForwardIcon.png").Reference, PdnResources.GetString("DocumentWorkspace.ShowFileDialog.SkipTB.ActionText"), PdnResources.GetString("DocumentWorkspace.ShowFileDialog.SkipTB.ExplanationText")); TaskButton cancelTB = new TaskButton( PdnResources.GetImageResource("Icons.CancelIcon.png").Reference, PdnResources.GetString("DocumentWorkspace.ShowFileDialog.CancelTB.ActionText"), PdnResources.GetString("DocumentWorkspace.ShowFileDialog.CancelTB.ExplanationText")); List taskButtons = new List(); taskButtons.Add(retryTB); // Only have the Skip button if there is more than 1 item being transferred. // If only 1 item is begin transferred, Skip and Cancel are essentially synonymous. if (this.itemCount > 1) { taskButtons.Add(skipTB); } taskButtons.Add(cancelTB); int width96 = (TaskDialog.DefaultPixelWidth96Dpi * 4) / 3; TaskButton clickedTB = TaskDialog.Show( this.progressDialog, formIcon, formTitle, taskImage, true, introText, taskButtons.ToArray(), retryTB, cancelTB, width96, false, 0, out bool unuse); if (clickedTB == retryTB) { result = WorkItemFailureAction.RetryItem; } else if (clickedTB == skipTB) { result = WorkItemFailureAction.SkipItem; } else { result = WorkItemFailureAction.CancelOperation; } return result; } private void UpdateUI() { int itemCount2 = Math.Max(1, this.itemCount); double startValue = (double)this.itemOrdinal / (double)itemCount2; double endValue = (double)(this.itemOrdinal + 1) / (double)itemCount2; long totalWork2 = Math.Max(1, this.totalWork); double lerp = (double)this.totalProgress / (double)totalWork2; double newValue = Utility.Lerp(startValue, endValue, lerp); int newValueInt = (int)Math.Ceiling(maxPBValue * newValue); if (this.cancelRequested) { this.progressDialog.CancelEnabled = false; //this.progressDialog.ItemText = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ItemText.Canceling"); //this.progressDialog.OperationProgress = string.Empty; this.progressDialog.ProgressBar.Style = ProgressBarStyle.Marquee; } else { this.progressDialog.CancelEnabled = true; //this.progressDialog.ItemText = this.itemName; string progressFormat = PdnResources.GetString("DocumentWorkspace.ShowFileDialog.ProgressText.Format"); string progressText = string.Format(progressFormat, this.itemOrdinal + 1, this.itemCount); //this.progressDialog.OperationProgress = progressText; this.progressDialog.ProgressBar.Style = ProgressBarStyle.Continuous; this.progressDialog.ProgressBar.Value = newValueInt; } } } public static DialogResult ChooseFiles(Control owner, out string[] fileNames, bool multiselect, string startingDir) { using (IFileOpenDialog ofd = new ClassicFileOpenDialog()) { ofd.InitialDirectory = ""; if (startingDir != null) { ofd.InitialDirectory = startingDir; } ofd.CheckFileExists = true; ofd.CheckPathExists = true; ofd.Multiselect = multiselect; ofd.Filter = PdnResources.GetString("NewRasterData") + "(*.tif,*.tiff,*.jpg,*.jpeg,*.png,*.bmp)|*.tif;*.tiff;*.jpg;*.jpeg;*.png;*.bmp"; ofd.FilterIndex = 0; DialogResult result = ShowFileDialog(owner, ofd); if (result == DialogResult.OK) { fileNames = ofd.FileNames; } else { fileNames = new string[0]; } return result; } } /// /// 图片保存,保存当前激活图片,用来替换原框架的保存 /// 1)若当前打开的非硬盘打开图片,点击保存,系统打开保存路径窗口(图1) /// 若命名在保存路径重复,则打开对应提示窗口,具体效果可点击图1中的【保存】按钮查看效果 /// 2)若硬盘图像未保存点击保存按钮,根据系统设置进行保存,写死设置为: /// 生成配置文件、不保存网格数据、不嵌入标注及测量信息、保存后不关闭图像、不压缩图像 /// /// public bool DoSaveNew() { string newFileName; GetDocumentSaveOptions(out newFileName); // 如果没有指定文件名(不是从硬盘打开,是生成或从相机获得),则执行另存为 if (newFileName == null) { return DoSaveAsNew(); } else { try { //获取文件后缀名 string extension = Path.GetExtension(newFileName); //保存图片,保存原路径、原文件名、原保存格式、不压缩、保存后不关闭图像、不保存相 using (Bitmap bitmap = this.CompositionSurface.CreateAliasedBitmap()) { //保存图片 if (!extension.Equals(".tga"))//不是压缩包 { ImageCodecInfo icf = ImageBaseHelper.GetImageCodecInfo(ImageFormat.Jpeg); if (extension.Equals(".jpg")) { icf = ImageBaseHelper.GetImageCodecInfo(ImageFormat.Jpeg); } else if (extension.Equals(".bmp")) { icf = ImageBaseHelper.GetImageCodecInfo(ImageFormat.Bmp); } else if (extension.Equals("TIFF")) { icf = ImageBaseHelper.GetImageCodecInfo(ImageFormat.Tiff); } EncoderParameters parms = new EncoderParameters(1); EncoderParameter parm = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L); parms.Param[0] = parm; bitmap.Save(newFileName, icf, parms); } } } catch (Exception) { MessageBox.Show(PdnResources.GetString("Menu.Imagesavefailed.text")); return false; } } return true; } /// /// 获取批量保存中设置的参数,按生成规律提取文件名称 /// /// 文件名称 /// public bool GetParameters(out string file_Name) { file_Name = string.Empty; batchSaveAutoModel = XmlSerializeHelper.DESerializer(FileOperationHelper.ReadStringFromFile(Application.StartupPath + @"\Config\Default\File\BatchSaveAuto.xml", FileMode.Open)); if (batchSaveAutoModel.Whether) { file_Name = batchSaveAutoModel.prefix + batchSaveAutoModel.fileName + "_" + batchSaveAutoModel.startNum + batchSaveAutoModel.suffix; batchSaveAutoModel.startNum = batchSaveAutoModel.startNum + 1; //另存为XML string stageModelXml = XmlSerializeHelper.XmlSerialize(batchSaveAutoModel); string filePath = Application.StartupPath + @"\Config\Default\File\BatchSaveAuto.xml"; FileOperationHelper.WriteStringToFile(stageModelXml, filePath, FileMode.Create); } return batchSaveAutoModel.Whether; } /// /// 文件另存,用来替换原框架的保存 /// 1)将图片另存到其他位置,即变化不保存在原图像上 /// 2)点击另存为,打开保存路径窗口(图1) /// 3)并根据(图1)中对应的设置判断是否关闭打开的图像 /// 4)若名称重复,则弹出对应提示,查看效果可点击图1中的【保存】按钮 /// /// public bool DoSaveAsNew() { //获取批量保存中设置的参数,提取文件名称 string file_Name; //判断是否是压缩包文件 bool isZipFile = false; if (zipHandleHelper != null) isZipFile = true; using (SaveFileDialog saveDialog = new SaveFileDialog()) { ConfigModel configModel = Program.instance.configModel;//获取另存窗口几个选项的配置 File.MySaveDialogControl saveDialogCtrl = new File.MySaveDialogControl(@"C:\Users\dlrj\Desktop\晶粒度-冷轧薄板晶粒度评级2 - 副本.JPG"/*lblFilePath.Text*/, this); //saveDialogCtrl.FileDlgInitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); saveDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); //生成配置文件选中状态 if (configModel.WhetherGenerateConfig == 0) saveDialogCtrl.checkBox1.Checked = false; //关闭图像选中状态 if (configModel.WhetherCloseAfterSave == 0) saveDialogCtrl.checkBox2.Checked = false; if (isZipFile) { saveDialog.Filter = "Tga(*.tga)|*.tga"; saveDialog.DefaultExt = "tga"; saveDialogCtrl.checkBox5.Visible = false; saveDialogCtrl.numericUpDown1.Visible = false; saveDialogCtrl.label1.Visible = false; } else { //压缩比例选中状态 if (configModel.WhetherCompression == 1) saveDialogCtrl.checkBox5.Checked = true; saveDialogCtrl.numericUpDown1.Value = configModel.CompressionRatio;//压缩比例数值 saveDialog.Filter = "Jpeg(*.jpg)|*.jpg|Tiff(*.tiff)|*.tiff|Bmp(*.bmp)|*.bmp"; saveDialog.DefaultExt = "jpg"; } saveDialog.FilterIndex = 1; saveDialog.CheckFileExists = false;// true; saveDialog.AddExtension = true; string friendName = AppWorkspace.ActiveDocumentWorkspace.GetFriendlyName(); string m_FileName = Path.GetFileNameWithoutExtension(friendName);//friendName.Substring(friendName.LastIndexOf('\\') + 1, friendName.LastIndexOf('.') - friendName.LastIndexOf('\\') - 1); string suffixName = Path.GetExtension(friendName);//friendName.Substring(friendName.LastIndexOf(".") + 1, (friendName.Length - friendName.LastIndexOf(".") - 1)); ; //判断是否有保存参数,有则获取,无则使用原始文件名 if (GetParameters(out file_Name)) { saveDialog.FileName = file_Name; } else { saveDialog.FileName = m_FileName + " - " + PdnResources.GetString("Menu.Acopyofth.Text") + suffixName; } saveDialog.DereferenceLinks = true; //saveDialog.ShowHelp = true; if (Environment.OSVersion.Version.Major < 6) saveDialog.SetPlaces(new object[] { (int)Places.Desktop, (int)Places.Printers, (int)Places.Favorites, (int)Places.Programs, (int)Places.Fonts, }); string path = ""; if (saveDialog.ShowDialog(saveDialogCtrl, this) == DialogResult.OK) { //文件路径 path = saveDialog.FileName; //是否生成配置文件 bool createConfig = saveDialogCtrl.checkBox1.Checked; //保存后是否关闭图像 bool afterSaveClost = saveDialogCtrl.checkBox2.Checked; //是否压缩 bool compress = saveDialogCtrl.checkBox5.Checked; //压缩比例 decimal compressRate = saveDialogCtrl.numericUpDown1.Value; //重新保存选项到配置文件 if (createConfig) configModel.WhetherGenerateConfig = 1; else configModel.WhetherGenerateConfig = 0; if (afterSaveClost) configModel.WhetherCloseAfterSave = 1; else configModel.WhetherCloseAfterSave = 0; if (compress) configModel.WhetherCompression = 1; else configModel.WhetherCompression = 0; configModel.CompressionRatio = compressRate; string configModelXml = XmlSerializeHelper.XmlSerialize(configModel); FileOperationHelper.WriteStringToFile(configModelXml, Application.StartupPath + "\\Config\\" + Program.instance.SettingPrefix + "\\Config.xml", FileMode.Create); //保存图片,保存原路径、原文件名、原保存格式、不压缩、保存后不关闭图像 using (Bitmap bitmap = this.CompositionSurface.CreateAliasedBitmap()) { //获取文件后缀名 string extension = Path.GetExtension(path); if (!extension.Equals(".tga")) { using (Bitmap dstBitmap = bitmap.Clone(new Rectangle(0, 0, bitmap.Width, bitmap.Height), bitmap.PixelFormat)) { Graphics graphics = Graphics.FromImage(dstBitmap); //保存图片 ImageCodecInfo icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Jpeg); if (extension.Equals(".jpg")) { icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Jpeg); } else if (extension.Equals(".bmp")) { icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Bmp); } else if (extension.Equals(".tiff")) { icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Tiff); } EncoderParameters parms = new EncoderParameters(1); EncoderParameter parm = new EncoderParameter(Encoder.Quality, (compress && compressRate > 0) ? long.Parse(compressRate.ToString()) : 100L); parms.Param[0] = parm; dstBitmap.Save(path, icf, parms); } } else { //另存的路径与原zip路径不相同,则copy一份;相同不做处理 if (!path.Equals(zipHandleHelper.zipName)) { System.IO.File.Copy(zipHandleHelper.zipName, path, true); } } //保存配置文件 if (createConfig) { //组织配置文件的数据 PicConfigModel picConfigModel = new PicConfigModel(); //picConfigModel.others = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Other); picConfigModel.hardware = new PicConfigModel.Hardware(); ////相机参数赋值 //GetCameraParameters(picConfigModel); picConfigModel.meta = new PicConfigModel.Meta(); picConfigModel.rule = new PicConfigModel.Rule(); picConfigModel.meta.format = extension; picConfigModel.meta.createdTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); if ((this.existenceXML && this.xmlSaveModel != null && this.xmlSaveModel != null && this.xmlSaveModel.pixel_length != 0) || (this.xmlSaveModel != null && this.xmlSaveModel.pixel_length != 0)) { picConfigModel.rule.ruler_name = this.xmlSaveModel.ruler_name; picConfigModel.rule.gain_multiple = this.xmlSaveModel.gain_multiple; picConfigModel.rule.pixel_length = (int)this.xmlSaveModel.pixel_length; picConfigModel.rule.physical_length = this.xmlSaveModel.physical_length; picConfigModel.rule.ruler_units = this.xmlSaveModel.ruler_units; } else { if (Program.instance.ruleDB != null) { picConfigModel.rule.ruler_name = Program.instance.ruleDB.ruler_name; picConfigModel.rule.gain_multiple = Program.instance.ruleDB.gain_multiple; picConfigModel.rule.pixel_length = (int)Program.instance.ruleDB.pixel_length; picConfigModel.rule.physical_length = Program.instance.ruleDB.physical_length; picConfigModel.rule.ruler_units = Program.instance.ruleDB.ruler_units; } } FileInfo fileInfo = new FileInfo(path); long lengthOfDocument = fileInfo.Length; picConfigModel.meta.imageSize = FileOperationHelper.GetLength(lengthOfDocument); //获取图像所在的目录 string directoryPath = Path.GetDirectoryName(path); //获取不带后缀的文件名 string noExtension = Path.GetFileNameWithoutExtension(path); picConfigModel.meta.text = noExtension; //按路径和名称保存xml文件 string userInfoXml = XmlSerializeHelper.XmlSerialize(picConfigModel); //xml保存路径 string filePath = directoryPath + "\\" + noExtension + ".xml"; //保存xml FileOperationHelper.WriteStringToFile(userInfoXml, filePath, FileMode.Create); if (extension.Equals(".tga")) { //copy了新的zip包,则修改新zip包内的xml if (!path.Equals(zipHandleHelper.zipName)) { ZipHandleHelper newZipFile = new ZipHandleHelper(path); //if (newZipFile != null) //{ // if (!newZipFile.ModifyLabelAndMeasureXml(picConfigModel)) // MessageBox.Show(PdnResources.GetString("Menu.Annotatiovingfailed.text")); //} } //没有copy,修改旧zip包的xml else { //if (!zipHandleHelper.ModifyLabelAndMeasureXml(picConfigModel)) // MessageBox.Show(PdnResources.GetString("Menu.Annotatiovingfailed.text")); } } //if (!extension.Equals(".tga"))//压缩包不清楚是否要保存基础和标尺等信息 //{ // picConfigModel.meta = new PicConfigModel.Meta(); // picConfigModel.rule = new PicConfigModel.Rule(); // picConfigModel.meta.format = extension; // picConfigModel.meta.createdTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); // if ((this.existenceXML && this.xmlSaveModel != null && this.xmlSaveModel != null && this.xmlSaveModel.pixel_length != 0) || (this.xmlSaveModel != null && this.xmlSaveModel.pixel_length != 0)) // { // picConfigModel.rule.ruler_name = this.xmlSaveModel.ruler_name; // picConfigModel.rule.gain_multiple = this.xmlSaveModel.gain_multiple; // picConfigModel.rule.pixel_length = (int)this.xmlSaveModel.pixel_length; // picConfigModel.rule.physical_length = this.xmlSaveModel.physical_length; // picConfigModel.rule.ruler_units = this.xmlSaveModel.ruler_units; // } // else // { // if (Program.instance.ruleDB != null) // { // picConfigModel.rule.ruler_name = Program.instance.ruleDB.ruler_name; // picConfigModel.rule.gain_multiple = Program.instance.ruleDB.gain_multiple; // picConfigModel.rule.pixel_length = (int)Program.instance.ruleDB.pixel_length; // picConfigModel.rule.physical_length = Program.instance.ruleDB.physical_length; // picConfigModel.rule.ruler_units = Program.instance.ruleDB.ruler_units; // } // } // FileInfo fileInfo = new FileInfo(path); // long lengthOfDocument = fileInfo.Length; // picConfigModel.meta.imageSize = FileOperationHelper.GetLength(lengthOfDocument); // //获取图像所在的目录 // string directoryPath = Path.GetDirectoryName(path); // //获取不带后缀的文件名 // string noExtension = Path.GetFileNameWithoutExtension(path); // picConfigModel.meta.text = noExtension; // //按路径和名称保存xml文件 // string userInfoXml = XmlSerializeHelper.XmlSerialize(picConfigModel); // //xml保存路径 // string filePath = directoryPath + "\\" + noExtension + ".xml"; // //保存xml // FileOperationHelper.WriteStringToFile(userInfoXml, filePath, FileMode.Create); //} //else //{ // //copy了新的zip包,则修改新zip包内的xml // if (!path.Equals(zipHandleHelper.zipName)) // { // ZipHandleHelper newZipFile = new ZipHandleHelper(path); // if (newZipFile != null) // { // if (!newZipFile.ModifyLabelAndMeasureXml(picConfigModel)) // MessageBox.Show(PdnResources.GetString("Menu.Annotatiovingfailed.text")); // } // } // //没有copy,修改旧zip包的xml // else // { // if (!zipHandleHelper.ModifyLabelAndMeasureXml(picConfigModel)) // MessageBox.Show(PdnResources.GetString("Menu.Annotatiovingfailed.text")); // } //} } if (this.Document != null) { this.Document.Dirty = false; } //保存后是否关闭图像 if (afterSaveClost) { this.AppWorkspace.PerformAction(new CloseWorkspaceAction()); } else { this.filePath = path; this.fileText = this.GetFriendlyName(); this.AppWorkspace.ToolBar.DocumentStrip.SelectDocumentWorkspace(this); } } } else { return false; } } return true; } public static Document LoadDocument(Control owner, string fileName, ProgressEventHandler progressCallback) { Document document = null; using (new WaitCursorChanger(owner)) { //Utility.GCFullCollect(); //Stream stream = null; using (OpenCvSharp.Mat tempMat = new Mat(fileName)) { try { try { //stream = tempMat.ToMemoryStream(Path.GetExtension(fileName)); //long totalBytes = 0; //SiphonStream siphonStream = new SiphonStream(stream); /*IOEventHandler ioEventHandler = null; ioEventHandler = delegate (object sender, IOEventArgs e) { if (progressCallback != null) { totalBytes += (long)e.Count; double percent = Utility.Clamp(100.0 * ((double)totalBytes / (double)siphonStream.Length), 0, 100); progressCallback(null, new ProgressEventArgs(percent)); } };*/ //siphonStream.IOFinished += ioEventHandler; using (new WaitCursorChanger(owner)) { document = Document.FromMat(tempMat);// fileType.Load(siphonStream);// /*if (progressCallback != null) { progressCallback(null, new ProgressEventArgs(100.0)); }*/ } //siphonStream.IOFinished -= ioEventHandler; //siphonStream.Close(); GC.Collect(); } catch (WorkerThreadException ex) { Type innerExType = ex.InnerException.GetType(); ConstructorInfo ci = innerExType.GetConstructor(new Type[] { typeof(string), typeof(Exception) }); if (ci == null) { throw; } else { Exception ex2 = (Exception)ci.Invoke(new object[] { "Worker thread threw an exception of this type", ex.InnerException }); throw ex2; } } } catch (ArgumentException) { if (fileName.Length == 0) { Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.BlankFileName")); } else { Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.ArgumentException")); } } catch (UnauthorizedAccessException) { Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.UnauthorizedAccessException")); } catch (SecurityException) { Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.SecurityException")); } catch (FileNotFoundException) { Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.FileNotFoundException")); } catch (DirectoryNotFoundException) { Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.DirectoryNotFoundException")); } catch (PathTooLongException) { Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.PathTooLongException")); } catch (IOException) { Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.IOException")); } catch (SerializationException) { Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.SerializationException")); } catch (OutOfMemoryException) { Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.OutOfMemoryException")); } catch (Exception) { Utility.ErrorBox(owner, PdnResources.GetString("LoadImage.Error.Exception")); } finally { /*if (stream != null) { stream.Close(); stream = null; }*/ /*if (tempMat != null) { tempMat.Dispose(); }*/ } } } return document; } /// /// 批量保存 /// /// 文件名 /// 是否生成配置文件 /// 保存后是否关闭图像 /// 保存时是否保存网格数据 /// 标注及测量信息是否嵌入图像 /// 是否压缩 /// 压缩比例 /// public bool SaveForBatch(string fileName, bool createConfig, bool afterSaveClost, bool saveGridLine, bool implantLabelAndMeasure, bool compress, decimal compressRate, bool implantPhase) { //保存图片,保存原路径、原文件名、原保存格式、不压缩、保存后不关闭图像 using (Bitmap bitmap = this.CompositionSurface.CreateAliasedBitmap()) { Graphics graphics = Graphics.FromImage(bitmap); //获取文件后缀名 string extension = Path.GetExtension(fileName); //保存图片 ImageCodecInfo icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Jpeg); if (extension.Equals(".jpg")) { icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Jpeg); } else if (extension.Equals(".bmp")) { icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Bmp); } else if (extension.Equals(".tiff")) { icf = GdiPlusFileType.GetImageCodecInfo(ImageFormat.Tiff); } EncoderParameters parms = new EncoderParameters(1); EncoderParameter parm = new EncoderParameter(Encoder.Quality, (compress && compressRate > 0) ? long.Parse(compressRate.ToString()) : 100L); parms.Param[0] = parm; bitmap.Save(fileName, icf, parms); //保存配置文件 if (createConfig) { //组织配置文件的数据 PicConfigModel picConfigModel = new PicConfigModel(); picConfigModel.hardware = new PicConfigModel.Hardware(); //picConfigModel.others = this.GraphicsList.GetLabelsOrMeasureData(DrawClass.Other); picConfigModel.meta = new PicConfigModel.Meta(); picConfigModel.rule = new PicConfigModel.Rule(); if (this.xmlSaveModel != null) { picConfigModel.rule.ruler_name = this.xmlSaveModel.ruler_name; picConfigModel.rule.gain_multiple = this.xmlSaveModel.gain_multiple; picConfigModel.rule.pixel_length = (int)this.xmlSaveModel.pixel_length; picConfigModel.rule.physical_length = this.xmlSaveModel.physical_length; picConfigModel.rule.ruler_units = this.xmlSaveModel.ruler_units; } //GetCameraParameters(picConfigModel); //获取图像所在的目录 string directoryPath = Path.GetDirectoryName(fileName); //获取不带后缀的文件名 string noExtension = Path.GetFileNameWithoutExtension(fileName); //按路径和名称保存xml文件 string userInfoXml = XmlSerializeHelper.XmlSerialize(picConfigModel); //xml保存路径 string filePath = directoryPath + "\\" + noExtension + ".xml"; //保存xml FileOperationHelper.WriteStringToFile(userInfoXml, filePath, FileMode.Create); } if (this.Document != null) { this.Document.Dirty = false; } //保存后是否关闭图像 if (afterSaveClost) { this.Document.Dirty = false; this.AppWorkspace.toRemoveDocumentWorkspaceIndex = this.AppWorkspace.DocumentWorkspaces.Length - 1; this.AppWorkspace.PerformAction(new CloseWorkspaceAction()); } else { this.filePath = fileName; this.fileText = this.GetFriendlyName(); this.AppWorkspace.ToolBar.DocumentStrip.SelectDocumentWorkspace(this); } } return true; } /// /// 更新测量单位,刷新UI /// /// public void UpdateMeasureUnit(MeasurementUnit measurementUnit) { //循环所有测量,更新单位 if (this.GraphicsList != null && this.GraphicsList.Count > 0) { int count = this.GraphicsList.Count; for (int i = 0; i < count; i++) { if (this.GraphicsList[i].objectType == DrawClass.Measure) { ((MeasureDrawObject)(this.GraphicsList[i])).MeasurementUnit = measurementUnit; } } } this.Refresh(); } protected override string[] startUpRules(Dictionary rules) { string[] result = new string[5]; result[0] = Program.instance.measurementUnit.ToString(); result[1] = InvariantData.unitsDictionary[(int)Program.instance.measurementUnit]; result[2] = InvariantData.unitSymbolsDictionary[(int)Program.instance.measurementUnit]; if (rules != null) { result[3] = (rules[Program.instance.measurementUnit]).ToString(); result[4] = (rules[MeasurementUnit.Micron]).ToString(); } else { result[3] = (Program.instance.rules[Program.instance.measurementUnit]).ToString(); result[4] = (Program.instance.rules[MeasurementUnit.Micron]).ToString(); } return result; } public override void ToolStripMenuItem1_Click(object sender, EventArgs e) { using (MeasureSettingDialog af = new MeasureSettingDialog(AppWorkspace)) { af.StartPosition = FormStartPosition.CenterScreen; af.ShowDialog(); } } public override void ToolStripMenuItem3_Click(object sender, EventArgs e) { for (int i = 0; i < this.GraphicsList.Count; i++) { if (GraphicsList[i].Selected) { MeasurementPropertiesDialog measurementPropertiesDialog = new MeasurementPropertiesDialog(this.appWorkspace, this.GraphicsList[i]); measurementPropertiesDialog.StartPosition = FormStartPosition.CenterScreen; measurementPropertiesDialog.ShowDialog(); } } } } }