/// <summary> /// Runs template finalization /// </summary> private void OnFinilizeTemplate() { BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += (sender, args) => { string templateData = TemplateSerializer.TemplateToJson(this, false); string additionalPars = string.Empty; try { string templateName = Path.GetFileNameWithoutExtension(this.TemplateImageName) + "_template.omr"; FinalizationData finalizationResult = CoreApi.FinalizeTemplate(templateName, Encoding.UTF8.GetBytes(templateData), this.TemplateId, additionalPars); Application.Current.Dispatcher.Invoke(() => { this.ProcessFinalizationResponse(finalizationResult); }); } catch (Exception e) { DialogManager.ShowErrorDialog(e.Message); } }; worker.RunWorkerCompleted += (sender, args) => { BusyIndicatorManager.Disable(); }; BusyIndicatorManager.Enable(); worker.RunWorkerAsync(); }
/// <summary> /// Performs template save routine by specified path /// </summary> /// <param name="path">Path to save template</param> private void SaveTemplateByPath(string path) { if (this.SelectedTab is TemplateViewModel) { TemplateViewModel template = this.SelectedTab as TemplateViewModel; template.TemplateName = Path.GetFileNameWithoutExtension(path); // save .omr template data string jsonRes = TemplateSerializer.TemplateToJson(template); File.WriteAllText(path, jsonRes); path = path.Replace(".omr", template.ImageFileFormat); // save template image // if by some reason copy wasn't successful, manually save template image as png if (!string.IsNullOrEmpty(template.TempImagePath)) { if (!ImageProcessor.CopyUserTemplateImage(template.TempImagePath, path)) { path = path.Replace(template.ImageFileFormat, ".png"); ImageProcessor.SaveTemplateImage(template.TemplateImage, path); } } else { path = path.Replace(template.ImageFileFormat, ".png"); ImageProcessor.SaveTemplateImage(template.TemplateImage, path); } template.IsDirty = false; template.LoadedPath = path; } }
/// <summary> /// Loads template by specified path /// </summary> /// <param name="file">Path to template file</param> private void LoadTemplateFromFile(string file) { string jsonString = File.ReadAllText(file); TemplateViewModel tempalteViewModel = TemplateSerializer.JsonToTemplate(jsonString); this.TabViewModels.Add(tempalteViewModel); this.SelectedTab = tempalteViewModel; }
/// <summary> /// Performs recognition for provided image /// </summary> /// <param name="itemToProcess">Image to process</param> private void RecognizeImageRoutine(ImagePreviewViewModel itemToProcess) { // check if image was already processed if (itemToProcess.IsProcessed) { // ask user confirmation if (!DialogManager.ShowConfirmDialog( string.Format("Image {0} was already recognized. Are you sure you want to run recognition again?", itemToProcess.Title))) { // if no confirmation, clean up and return itemToProcess.IsProcessing = false; itemToProcess.StatusText = string.Empty; return; } } itemToProcess.CanCancel = false; itemToProcess.StatusText = "Preparing for dispatch..."; var image = new BitmapImage(new Uri("file://" + itemToProcess.PathToImage)); byte[] imageData = TemplateSerializer.CompressImage(image, itemToProcess.ImageSizeInBytes); //string imageData = TemplateConverter.CheckAndCompressImage(image, itemToProcess.ImageFileFormat, itemToProcess.ImageSizeInBytes); string additionalPars = string.Empty; itemToProcess.StatusText = "Core processing..."; try { string result = CoreApi.RecognizeImage(itemToProcess.Title, imageData, this.templateId, itemToProcess.WasUploaded, additionalPars); Application.Current.Dispatcher.Invoke(() => { this.ProcessResult(result, itemToProcess); // update item states itemToProcess.WasUploaded = true; itemToProcess.IsProcessing = false; itemToProcess.StatusText = string.Empty; itemToProcess.CanCancel = true; }); } catch (Exception e) { // clean up in case of exception itemToProcess.IsProcessing = false; itemToProcess.StatusText = string.Empty; itemToProcess.CanCancel = true; DialogManager.ShowErrorDialog(e.Message); } }
/// <summary> /// Runs template correction /// </summary> private void OnCorrectTemplate() { BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += (sender, args) => { string templateData = TemplateSerializer.TemplateToJson(this, false); byte[] imageData = TemplateSerializer.CompressImage(this.TemplateImage, this.ImageSizeInBytes); //string imageData = TemplateConverter.CheckAndCompressImage(this.TemplateImage, this.ImageFileFormat, this.ImageSizeInBytes); string additionalPars = string.Empty; try { TemplateViewModel correctedTemplate = CoreApi.CorrectTemplate(this.TemplateImageName, imageData, templateData, this.WasUploaded, additionalPars); Application.Current.Dispatcher.Invoke(() => { this.ClearSelection(); this.PageQuestions.Clear(); this.AddQuestions(correctedTemplate.PageQuestions); this.TemplateId = correctedTemplate.TemplateId; this.FinalizationComplete = false; double koeff = this.TemplateImage.PixelWidth / correctedTemplate.PageWidth; ZoomKoefficient *= koeff; this.OnPropertyChanged(nameof(this.PageScale)); this.PageWidth = correctedTemplate.PageWidth; this.PageHeight = correctedTemplate.PageHeight; this.WasUploaded = true; this.Warnings.Add("Template correction complete!"); }); } catch (Exception e) { DialogManager.ShowErrorDialog(e.Message); } }; worker.RunWorkerCompleted += (sender, args) => { BusyIndicatorManager.Disable(); }; BusyIndicatorManager.Enable(); worker.RunWorkerAsync(); }
/// <summary> /// Saves template /// </summary> private void OnSaveTemplate() { string savePath = DialogManager.ShowSaveTemplateDialog(); if (savePath == null) { return; } string jsonRes = TemplateSerializer.TemplateToJson(this, true); File.WriteAllText(savePath, jsonRes); }
/// <summary> /// Template generation completed handler /// </summary> /// <param name="generationResult">Generation result</param> private void GenerationCompleted(TemplateGenerationContent generationResult) { if (generationResult == null) { return; } TemplateViewModel templateViewModel = generationResult.Template; templateViewModel.TemplateImage = TemplateSerializer.DecompressImage(Convert.ToBase64String(generationResult.ImageData)); templateViewModel.TemplateImageName = templateViewModel.TemplateName + ".jpg"; templateViewModel.IsGeneratedTemplate = true; templateViewModel.IsDirty = true; this.AddTab(templateViewModel); }
public async Task <ActionResult> CreateEmptyTemplate(product product) { const double pixelSize = 37.938105; double width = double.Parse(product.Width) * pixelSize;; double height = double.Parse(product.Height) * pixelSize;; TemplateSerializer TemplateJson = new TemplateSerializer { Width = width, Height = height, Images = new List <TemplateImage>(), TextBlocks = new List <TemplateText>() }; TemplateImage main_image = new TemplateImage { Name = "MainImage", Src = product.PicturePath, Width = width, Height = height, Top = 0, Left = 0, }; TemplateJson.Images.Add(main_image); Template NewTemplate = new Template { ProductId = product.Id, Name = product.Name, UserId = 1, JsonTemplate = JsonSerializer.Serialize <TemplateSerializer>(TemplateJson), DateCreated = DateTime.Now.ToShortDateString(), }; await db.Template.AddAsync(NewTemplate); await db.SaveChangesAsync(); product.TemplateId = NewTemplate.Id; db.product.Update(product); await db.SaveChangesAsync(); return(RedirectToAction("Editor", "Editor", new { templateId = NewTemplate.Id })); }
public void Init() { Configuration = new uSyncCoreConfig(); ContentTypeSerializer = new ContentTypeSerializer(Constants.Packaging.DocumentTypeNodeName); MediaTypeSerializer = new MediaTypeSerializer("MediaType"); MemberTypeSerializer = new MemberTypeSerializer("MemberType"); TemplateSerializer = new TemplateSerializer(Constants.Packaging.TemplateNodeName); LanguageSerializer = new LanguageSerializer("Language"); DictionarySerializer = new DictionarySerializer(Constants.Packaging.DictionaryItemNodeName); MacroSerializer = new MacroSerializer(Constants.Packaging.MacroNodeName); DataTypeSerializer = new DataTypeSerializer(Constants.Packaging.DataTypeNodeName); ContentSerializer = new ContentSerializer(); MediaSerializer = new MediaSerializer(); MediaFileMover = new uSyncMediaFileMover(); }
public async Task <string> SaveTemplate([FromBody] TemplateSerializer data) { string webRoot = Path.Combine(_env.WebRootPath, "images"); string date = DateTime.Now.ToShortDateString(); string path = Path.Combine(webRoot, date); if (!System.IO.File.Exists(path)) { Directory.CreateDirectory(path); } for (int i = 0; i < data.Images.Count(); i++) { if (!data.Images[i].Src.Contains("/images/")) { byte[] ImageByte = Convert.FromBase64String(data.Images[i].Src); var file = Path.Combine(path, data.Images[i].Name + ".png"); System.IO.File.WriteAllBytes(file, ImageByte); string url = Path.Combine("/images/", date + "/", data.Images[i].Name + ".png"); data.Images[i].Src = url; } } if (data.Texture.TextureName != null) { byte[] MainTexture = Convert.FromBase64String(data.Texture.TextureSrc); var MainTextureFile = Path.Combine(path, data.Texture.TextureName); System.IO.File.WriteAllBytes(MainTextureFile, MainTexture); string TextureUrl = "/images/" + date + "/"; data.Texture.TextureSrc = TextureUrl; } Template template = await db.Template.FirstOrDefaultAsync(x => x.Id == data.templateId); template.JsonTemplate = JsonSerializer.Serialize <TemplateSerializer>(data); db.Template.Update(template); await db.SaveChangesAsync(); return("Макет был успешно сохранён!"); }
/// <summary> /// Loads template by specified path /// </summary> /// <param name="file">Path to template file</param> private void LoadTemplateFromFile(string file) { // return if there is active tabs and action was cancelled if (!this.CloseActiveTemplateTab()) { return; } if (!File.Exists(file)) { DialogManager.ShowErrorDialog("Failed to find file " + file + "."); return; } string directory = Path.GetDirectoryName(file); if (string.IsNullOrEmpty(directory)) { DialogManager.ShowErrorDialog("Failed to load template image."); return; } string templateName = Path.GetFileNameWithoutExtension(file); // find files with image extension and template name in the same directory List <string> imageFiles = DialogManager.GetImageFilesFromDirectory(directory) .Where(x => Path.GetFileNameWithoutExtension(x).Equals(templateName)).ToList(); if (imageFiles.Count < 1) { DialogManager.ShowErrorDialog("Failed to find template image."); return; } if (imageFiles.Count > 1) { DialogManager.ShowErrorDialog("Failed to load template image. Found several files with name: " + Path.GetFileNameWithoutExtension(file) + "."); return; } // load and deserialize template data try { string jsonString = File.ReadAllText(file); TemplateViewModel templateViewModel = TemplateSerializer.JsonToTemplate(jsonString); // if no name in template, use name of the file if (string.IsNullOrEmpty(templateViewModel.TemplateName)) { templateViewModel.TemplateName = Path.GetFileNameWithoutExtension(file); } // load image and check if it was loaded bool imageLoaded = templateViewModel.LoadTemplateImageFromFile(imageFiles[0]); if (!imageLoaded) { return; } templateViewModel.LoadedPath = file; templateViewModel.IsDirty = false; this.CloseActiveTemplateTab(); this.AddTab(templateViewModel); RecentMenuManager.AddFileNameToRecentList(this.RecentFiles, file); } catch (SerializationException e) { DialogManager.ShowErrorDialog("Failed to read or deserialize the template.\nReason: " + e.Message); return; } catch (Exception e) { DialogManager.ShowErrorDialog("Unknown error while loading the template.\nError details: " + e.Message); return; } }