public async void ReloadImage(bool allowFail = true) // Returns false on error { try { string path = Program.lastFilename; File.Copy(path, Paths.tempImgPath, true); bool fillAlpha = !bool.Parse(Config.Get("alpha")); await ImageProcessing.ConvertImage(path, ImageProcessing.Format.PngRaw, fillAlpha, ImageProcessing.ExtMode.UseNew, false, Paths.tempImgPath, true); previewImg.Image = ImgUtils.GetImage(Paths.tempImgPath); MainUIHelper.currentScale = 1; previewImg.ZoomToFit(); lastZoom = previewImg.Zoom; } catch (Exception e) { Logger.Log("Failed to reload image from source path - Maybe image is from clipboard or has been deleted. " + e.Message); if (!allowFail) { Logger.ErrorMessage("Failed to load image:", e); failed = true; } } }
public static async void UpscalePreview(bool fullImage = false) { if (!HasValidModelSelection()) { Program.ShowMessage("Invalid model selection.\nMake sure you have selected a model and that the file still exists.", "Error"); return; } if (Config.Get("cudaFallback").GetInt() == 3 && !Program.mainForm.HasValidNcnnModelSelection()) { Program.ShowMessage("Invalid model selection - NCNN does not support interpolation or chaining.", "Error"); return; } Upscale.currentMode = Upscale.UpscaleMode.Preview; Program.mainForm.SetBusy(true); Program.mainForm.SetProgress(2f, "Preparing..."); Program.mainForm.resetState = new Cupscale.PreviewState(previewImg.Image, previewImg.Zoom, previewImg.AutoScrollPosition); await Task.Delay(20); ResetCachedImages(); IOUtils.ClearDir(Paths.imgInPath); IOUtils.ClearDir(Paths.previewPath); IOUtils.ClearDir(Paths.previewOutPath); ESRGAN.PreviewMode prevMode = ESRGAN.PreviewMode.Cutout; if (fullImage) { prevMode = ESRGAN.PreviewMode.FullImage; if (!IOUtils.TryCopy(Paths.tempImgPath, Path.Combine(Paths.previewPath, "preview.png"), true)) { return; } } else { SaveCurrentCutout(); } ClipboardComparison.originalPreview = (Bitmap)ImgUtils.GetImage(Directory.GetFiles(IO.Paths.previewPath, "*.png.*", SearchOption.AllDirectories)[0]); await ImageProcessing.PreProcessImages(Paths.previewPath, !bool.Parse(Config.Get("alpha"))); string tilesize = Config.Get("tilesize"); bool alpha = bool.Parse(Config.Get("alpha")); ESRGAN.Backend backend = ESRGAN.Backend.CUDA; if (Config.Get("cudaFallback").GetInt() == 1) { backend = ESRGAN.Backend.CPU; } if (Config.Get("cudaFallback").GetInt() == 3) { backend = ESRGAN.Backend.NCNN; } sw.Restart(); if (currentMode == Mode.Single) { string mdl1 = Program.currentModel1; if (string.IsNullOrWhiteSpace(mdl1)) { return; } ModelData mdl = new ModelData(mdl1, null, ModelData.ModelMode.Single); await ESRGAN.DoUpscale(Paths.previewPath, Paths.previewOutPath, mdl, false, alpha, prevMode, backend); } if (currentMode == Mode.Interp) { string mdl1 = Program.currentModel1; string mdl2 = Program.currentModel2; if (string.IsNullOrWhiteSpace(mdl1) || string.IsNullOrWhiteSpace(mdl2)) { return; } ModelData mdl = new ModelData(mdl1, mdl2, ModelData.ModelMode.Interp, interpValue); await ESRGAN.DoUpscale(Paths.previewPath, Paths.previewOutPath, mdl, false, alpha, prevMode, backend); } if (currentMode == Mode.Chain) { string mdl1 = Program.currentModel1; string mdl2 = Program.currentModel2; if (string.IsNullOrWhiteSpace(mdl1) || string.IsNullOrWhiteSpace(mdl2)) { return; } ModelData mdl = new ModelData(mdl1, mdl2, ModelData.ModelMode.Chain); await ESRGAN.DoUpscale(Paths.previewPath, Paths.previewOutPath, mdl, false, alpha, prevMode, backend); } if (currentMode == Mode.Advanced) { ModelData mdl = new ModelData(null, null, ModelData.ModelMode.Advanced); await ESRGAN.DoUpscale(Paths.previewPath, Paths.previewOutPath, mdl, false, alpha, prevMode, backend); } if (!Program.cancelled) { Program.mainForm.SetProgress(0, $"Done - Upscaling took {(sw.ElapsedMilliseconds / 1000f).ToString("0.0")}s"); } Program.mainForm.SetBusy(false); }
private void MilkyLabel_Paint(object sender, PaintEventArgs e) { if (this.surface == null) { CreateSurface(); } PointF shadowPos = new PointF(0, 0); PointF textPos = new PointF(0, 0); SizeF allSize = this.Text.Measure(this.Font); using (Graphics g = Graphics.FromImage(this.surface)) { float height = 0; this.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None).ForAll((index, line) => { SizeF textSize = line.Measure(this.Font); int w = this.Width; int h = this.Height; w -= (this.Padding.Left + this.Padding.Right); h -= (this.Padding.Top + this.Padding.Bottom); //普通に描く場合のテキストの位置を計算する switch (this.TextAlign) { case ContentAlignment.TopLeft: case ContentAlignment.MiddleLeft: case ContentAlignment.BottomLeft: textPos.X = 0; break; case ContentAlignment.TopCenter: case ContentAlignment.MiddleCenter: case ContentAlignment.BottomCenter: textPos.X = (w - textSize.Width) / 2; break; case ContentAlignment.TopRight: case ContentAlignment.MiddleRight: case ContentAlignment.BottomRight: textPos.X = w - textSize.Width; break; } switch (this.TextAlign) { case ContentAlignment.TopLeft: case ContentAlignment.TopCenter: case ContentAlignment.TopRight: textPos.Y = height; break; case ContentAlignment.MiddleLeft: case ContentAlignment.MiddleCenter: case ContentAlignment.MiddleRight: textPos.Y = (h - allSize.Height) / 2 + height; break; case ContentAlignment.BottomLeft: case ContentAlignment.BottomCenter: case ContentAlignment.BottomRight: textPos.Y = h - allSize.Height + height; break; } //影の位置を計算する switch (this.shadowDir) { case ShadowDirection.TopLeft: shadowPos.X = textPos.X - shadowSize; shadowPos.Y = textPos.Y - shadowSize; break; case ShadowDirection.TopRight: shadowPos.X = textPos.X + shadowSize; shadowPos.Y = textPos.Y - shadowSize; break; case ShadowDirection.BottomLeft: shadowPos.X = textPos.X - shadowSize; shadowPos.Y = textPos.Y + shadowSize; break; case ShadowDirection.BottomRight: shadowPos.X = textPos.X + shadowSize; shadowPos.Y = textPos.Y + shadowSize; break; } textPos.X += this.Padding.Left; textPos.Y += this.Padding.Top; shadowPos.X += this.Padding.Left; shadowPos.Y += this.Padding.Top; height += textSize.Height; if (index == 0) { g.FillRectangle(new SolidBrush(this.BackColor), 0, 0, this.Width, this.Height); } if (shadowSize > 0) { g.SmoothingMode = SmoothingMode.HighQuality; g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; g.DrawString(line, this.Font, new SolidBrush(this.shadowColor), shadowPos); } if (shadowSize > 0) { g.SmoothingMode = SmoothingMode.HighQuality; g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; } g.DrawString(line, this.Font, new SolidBrush(this.ForeColor), textPos); }); } if (shadowSize > 0) { if (!ImgUtils.GaussianBlur(this.surface, this.shadowSize)) { throw new Exception(); } } using (Graphics g = Graphics.FromImage(this.surface)) { float height = 0; this.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None).ForAll((index, line) => { SizeF textSize = line.Measure(this.Font); int w = this.Width; int h = this.Height; w -= (this.Padding.Left + this.Padding.Right); h -= (this.Padding.Top + this.Padding.Bottom); //普通に描く場合のテキストの位置を計算する switch (this.TextAlign) { case ContentAlignment.TopLeft: case ContentAlignment.MiddleLeft: case ContentAlignment.BottomLeft: textPos.X = 0; break; case ContentAlignment.TopCenter: case ContentAlignment.MiddleCenter: case ContentAlignment.BottomCenter: textPos.X = (w - textSize.Width) / 2; break; case ContentAlignment.TopRight: case ContentAlignment.MiddleRight: case ContentAlignment.BottomRight: textPos.X = w - textSize.Width; break; } switch (this.TextAlign) { case ContentAlignment.TopLeft: case ContentAlignment.TopCenter: case ContentAlignment.TopRight: textPos.Y = height; break; case ContentAlignment.MiddleLeft: case ContentAlignment.MiddleCenter: case ContentAlignment.MiddleRight: textPos.Y = (h - allSize.Height) / 2 + height; break; case ContentAlignment.BottomLeft: case ContentAlignment.BottomCenter: case ContentAlignment.BottomRight: textPos.Y = h - allSize.Height + height; break; } textPos.X += this.Padding.Left; textPos.Y += this.Padding.Top; height += textSize.Height; g.SmoothingMode = SmoothingMode.HighQuality; g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; g.DrawString(line, this.Font, new SolidBrush(this.ForeColor), textPos); }); } e.Graphics.DrawImage(this.surface, 0, 0); }
public static async Task PostProcessImage(string path, Format format, bool dontResize) { Logger.Log($"[ImgProc] Post-Processing {Path.GetFileName(path)} to {format}, resize: {!dontResize}"); if (!dontResize) { ResizeImagePost(path); } MagickImage img = ImgUtils.GetMagickImage(path); string newExt = "png"; bool magick = true; if (format == Format.Source) { newExt = Path.GetExtension(path).Replace(".", ""); } if (format == Format.Png50) { img.Format = MagickFormat.Png; img.Quality = 50; } if (format == Format.PngFast) { img.Format = MagickFormat.Png; img.Quality = 20; } if (format == Format.Jpeg) { newExt = "jpg"; int q = Config.GetInt("jpegQ"); if (Config.GetBool("useMozJpeg")) { MozJpeg.Encode(path, GetOutPath(path, newExt, ExtMode.UseNew, ""), q); magick = false; } else { img.Format = MagickFormat.Jpeg; img.Quality = q; } } if (format == Format.Weppy) { img.Format = MagickFormat.WebP; img.Quality = Config.GetInt("webpQ"); if (img.Quality >= 100) { img.Settings.SetDefine(MagickFormat.WebP, "lossless", true); } newExt = "webp"; } if (format == Format.BMP) { img.Format = MagickFormat.Bmp; newExt = "bmp"; } if (format == Format.TGA) { img.Format = MagickFormat.Tga; newExt = "tga"; } if (format == Format.DDS) { magick = false; newExt = "tga"; await NvCompress.PngToDds(path, GetOutPath(path, newExt, ExtMode.UseNew, "")); } if (format == Format.GIF) { img.Format = MagickFormat.Gif; newExt = "gif"; } await Task.Delay(1); string outPath = GetOutPath(path, newExt, ExtMode.UseNew, ""); if (Upscale.currentMode == Upscale.UpscaleMode.Batch) { PostProcessingQueue.lastOutfile = outPath; } if (Upscale.currentMode == Upscale.UpscaleMode.Single || Upscale.currentMode == Upscale.UpscaleMode.Composition) { PreviewUI.lastOutfile = outPath; } if (magick) { img.Write(outPath); Logger.Log("[ImgProc] Written image to " + outPath); } if (outPath.ToLower() != path.ToLower()) { if (Logger.doLogIo) { Logger.Log("[ImgProc] Deleting source file: " + path); } File.Delete(path); } }
public static async Task ConvertImage(string path, Format format, bool fillAlpha, ExtMode extMode, bool deleteSource = true, string overrideOutPath = "", bool allowTgaFlip = false) { MagickImage img = ImgUtils.GetMagickImage(path, allowTgaFlip); string newExt = "png"; bool magick = true; Logger.Log($"[ImgProc] Converting {path} to {format}, DelSrc: {deleteSource}, Fill: {fillAlpha}, Ext: {extMode}"); if (format == Format.PngRaw) { img.Format = MagickFormat.Png32; img.Quality = 0; } if (format == Format.Png50) { img.Format = MagickFormat.Png32; img.Quality = 50; } if (format == Format.PngFast) { img.Format = MagickFormat.Png32; img.Quality = 20; } if (format == Format.Jpeg) { newExt = "jpg"; int q = Config.GetInt("jpegQ"); if (Config.GetBool("useMozJpeg")) { MozJpeg.Encode(path, GetOutPath(path, newExt, extMode, overrideOutPath), q); magick = false; } else { img.Format = MagickFormat.Jpeg; img.Quality = q; } } if (format == Format.Weppy) { img.Format = MagickFormat.WebP; img.Quality = Config.GetInt("webpQ"); if (img.Quality >= 100) { img.Settings.SetDefine(MagickFormat.WebP, "lossless", true); } newExt = "webp"; } if (format == Format.BMP) { img.Format = MagickFormat.Bmp; newExt = "bmp"; } if (format == Format.TGA) { img.Format = MagickFormat.Tga; newExt = "tga"; } if (format == Format.DDS) { magick = false; newExt = "tga"; await NvCompress.PngToDds(path, GetOutPath(path, newExt, ExtMode.UseNew, "")); } if (format == Format.GIF) { img.Format = MagickFormat.Gif; } if (magick) { img = CheckColorDepth(path, img); if (fillAlpha) { img = ImgUtils.FillAlphaWithBgColor(img); } } string outPath = GetOutPath(path, newExt, extMode, overrideOutPath); if (File.Exists(outPath)) { if (Logger.doLogIo) { Logger.Log("[ImgProc] File exists at - making sure it doesn't have readonly flag"); } IOUtils.RemoveReadonlyFlag(outPath); } bool inPathIsOutPath = outPath.ToLower() == path.ToLower(); if (inPathIsOutPath) // Force overwrite by deleting source file before writing new file - THIS IS IMPORTANT { File.Delete(path); } if (magick) { img.Write(outPath); Logger.Log("[ImgProc] Written image to " + outPath); } if (deleteSource && !inPathIsOutPath) { if (Logger.doLogIo) { Logger.Log("[ImgProc] Deleting source file: " + path); } File.Delete(path); } img.Dispose(); IOUtils.RemoveReadonlyFlag(outPath); await Task.Delay(1); }
public void ProcessRequest(HttpContext context) { var w = Utils.RequestQueryStringParam(context, "w"); var h = Utils.RequestQueryStringParam(context, "h"); var src = Utils.RequestQueryStringParam(context, "src"); var imgtype = Utils.RequestQueryStringParam(context, "imgtype"); if (h == "") { h = "0"; } if (w == "") { w = "0"; } if (Utils.IsNumeric(w) && Utils.IsNumeric(h)) { src = HttpContext.Current.Server.MapPath(src); var strCacheKey = context.Request.Url.Host.ToLower() + "*" + src + "*" + Utils.GetCurrentCulture() + "*img:" + w + "*" + h + "*"; var newImage = (Bitmap)Utils.GetCache(strCacheKey); if (newImage == null) { newImage = ImgUtils.CreateThumbnail(src, Convert.ToInt32(w), Convert.ToInt32(h)); Utils.SetCache(strCacheKey, newImage); } if ((newImage != null)) { context.Response.Clear(); context.Response.ClearHeaders(); ImageCodecInfo useEncoder; // due to issues on some servers not outputing the png format correctly from the thumbnailer. // this thumbnailer will always output jpg, unless specifically told to do a png format. if (imgtype.ToLower() == "png") { useEncoder = ImgUtils.GetEncoder(ImageFormat.Png); context.Response.ContentType = "image/png"; } else { useEncoder = ImgUtils.GetEncoder(ImageFormat.Jpeg); context.Response.ContentType = "image/jpeg"; } var encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 85L); try { context.Response.AddFileDependency(src); context.Response.Cache.SetETagFromFileDependencies(); context.Response.Cache.SetLastModifiedFromFileDependencies(); context.Response.Cache.SetCacheability(HttpCacheability.Public); newImage.Save(context.Response.OutputStream, useEncoder, encoderParameters); } catch (Exception exc) { var outArray = Utils.StrToByteArray(exc.ToString()); context.Response.OutputStream.Write(outArray, 0, outArray.Count()); } } } }
public static async void BeforeAfterAnim(bool save, bool h264) { string ext = "gif"; if (h264) { ext = "mp4"; } DialogForm dialogForm = new DialogForm("Creating comparison " + ext.ToUpper() + "..."); string tempPath = Path.Combine(IOUtils.GetAppDataDir(), "giftemp"); string framesPath = Path.Combine(tempPath, "frames"); IOUtils.ClearDir(tempPath); Directory.CreateDirectory(framesPath); resultPreview = (Bitmap)ImgUtils.GetImage(Directory.GetFiles(IO.Paths.previewOutPath, "*.png.*", SearchOption.AllDirectories)[0]); Image image1 = originalPreview; Image image2 = resultPreview; if (Config.GetInt("comparisonUseScaling") == 1) { image1 = (Bitmap)ImgUtils.GetImage(Path.Combine(IO.Paths.previewPath, "preview.png.png")); } float scale = (float)image2.Width / (float)image1.Width; Logger.Log("Scale for animation: " + scale); string outpath = Path.Combine(tempPath, "comparison." + ext); if (image2.Width <= 2048 && image2.Height <= 2048) { image1.Scale(scale, InterpolationMode.NearestNeighbor).Save(Path.Combine(framesPath, "0.png")); image2.Save(Path.Combine(framesPath, "1.png")); if (h264) { await FFmpegCommands.FramesToOneFpsMp4(framesPath, false, 14, 9, "", false); File.Move(Path.Combine(tempPath, "frames." + ext), outpath); } else { await FFmpeg.RunGifski(" -r 1 -W 2048 -q -o " + outpath.Wrap() + " \"" + framesPath + "/\"*.\"png\""); } if (save) { string comparisonSavePath = Path.ChangeExtension(Program.lastFilename, null) + "-comparison." + ext; File.Copy(outpath, comparisonSavePath, true); dialogForm.Close(); Program.ShowMessage("Saved current comparison to:\n\n" + comparisonSavePath, "Message"); } else { StringCollection paths = new StringCollection(); paths.Add(outpath); Clipboard.SetFileDropList(paths); dialogForm.Close(); Program.ShowMessage("The " + ext.ToUpper() + " file has been copied. You can paste it into any folder.\n" + "Please note that pasting it into Discord or other programs won't work as the clipboard can't hold animated images.", "Message"); } } else { Program.ShowMessage("The preview is too large for making an animation. Please create a smaller cutout or choose a different comparison type.", "Error"); } dialogForm.Close(); }
public static async void CopyToClipboardSideBySide(bool saveToFile, bool fullImage = false) { int footerHeight = 45; try { if (fullImage) { // this code is not used atm and probably does not work!! originalPreview = new Bitmap(ImgUtils.GetImage(Path.Combine(IO.Paths.previewOutPath, "preview-input-scaled.png"))); resultPreview = new Bitmap(ImgUtils.GetImage(Path.Combine(IO.Paths.previewOutPath, "preview-merged.png"))); } else { if (Config.GetInt("comparisonUseScaling") == 1) { originalPreview = (Bitmap)ImgUtils.GetImage(Directory.GetFiles(IO.Paths.previewPath, "*.png.*", SearchOption.AllDirectories)[0]); } resultPreview = (Bitmap)ImgUtils.GetImage(Directory.GetFiles(IO.Paths.previewOutPath, "*.png.*", SearchOption.AllDirectories)[0]); } } catch { Program.ShowMessage("Error creating clipboard preview!", "Error"); } int comparisonMod = 1; int newWidth = comparisonMod * resultPreview.Width, newHeight = comparisonMod * resultPreview.Height; Bitmap outputImage = new Bitmap(2 * newWidth, newHeight + footerHeight); string modelName = Program.lastModelName; using (Graphics graphics = Graphics.FromImage(outputImage)) { graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; graphics.InterpolationMode = InterpolationMode.NearestNeighbor; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.DrawImage(originalPreview, new Rectangle(0, 0, newWidth, newHeight), new Rectangle(new Point(), originalPreview.Size), GraphicsUnit.Pixel); graphics.DrawImage(resultPreview, new Rectangle(newWidth, 0, newWidth, newHeight), new Rectangle(new Point(), resultPreview.Size), GraphicsUnit.Pixel); Bitmap Bmp = new Bitmap(2 * newWidth, footerHeight); Color color = Color.FromArgb(22, 22, 22); using (Graphics gfx = Graphics.FromImage(Bmp)) using (SolidBrush brush = new SolidBrush(color)) { gfx.FillRectangle(brush, 0, 0, 2 * newWidth, footerHeight); } graphics.DrawImage(Bmp, 0, newHeight); GraphicsPath p = new GraphicsPath(); int fontSize = 19; SizeF s = new Size(999999999, 99999999); Font font = new Font("Times New Roman", graphics.DpiY * fontSize / 72); string barString = "[CS] " + Path.GetFileName(Program.lastFilename) + " - " + modelName; int cf = 0, lf = 0; while (s.Width >= 2 * newWidth) { fontSize--; font = new Font(FontFamily.GenericSansSerif, graphics.DpiY * fontSize / 72, FontStyle.Regular); s = graphics.MeasureString(barString, font, new SizeF(), new StringFormat(), out cf, out lf); } StringFormat stringFormat = new StringFormat(); stringFormat.Alignment = StringAlignment.Center; double a = graphics.DpiY * fontSize / 72; stringFormat.LineAlignment = StringAlignment.Center; double contrastW = GetColorContrast(color, Color.White); double contrastB = GetColorContrast(color, Color.Black); Brush textBrush = contrastW < 3.0 ? Brushes.Black : Brushes.White; graphics.DrawString($"{barString}", font, textBrush, new Rectangle(0, newHeight, 2 * newWidth, footerHeight - 0), stringFormat); } try { if (saveToFile) { await SaveComparisonToFile(outputImage); } else { Clipboard.SetDataObject(outputImage); } } catch { Program.ShowMessage("Failed to save comparison.", "Error"); } }
public static async void CopyToClipboardSlider(bool saveToFile, bool fullImage = false) { int footerHeight = 45; try { if (fullImage) { originalPreview = new Bitmap(ImgUtils.GetImage(Path.Combine(IO.Paths.previewOutPath, "preview-input-scaled.png"))); resultPreview = new Bitmap(ImgUtils.GetImage(Path.Combine(IO.Paths.previewOutPath, "preview-merged.png"))); } else { if (Config.GetInt("comparisonUseScaling") == 1) { originalPreview = (Bitmap)ImgUtils.GetImage(Path.Combine(IO.Paths.previewPath, "preview.png.png")); } resultPreview = (Bitmap)ImgUtils.GetImage(Path.Combine(IO.Paths.previewOutPath, "preview.png.tmp")); } } catch { Program.ShowMessage("Error creating clipboard preview!", "Error"); } int comparisonMod = 1; //int.TryParse(comparisonMod_comboBox.SelectedValue.ToString(), out comparisonMod); int newWidth = comparisonMod * resultPreview.Width, newHeight = comparisonMod * resultPreview.Height; Bitmap outputImage = new Bitmap(newWidth, newHeight + footerHeight); string modelName = Program.lastModelName; using (Graphics graphics = Graphics.FromImage(outputImage)) { graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; graphics.InterpolationMode = InterpolationMode.NearestNeighbor; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; graphics.CompositingQuality = CompositingQuality.HighQuality; int halfWidth = (int)Math.Round(newWidth * 0.5f); Bitmap croppedOutput = resultPreview.Clone(new Rectangle(halfWidth, 0, newWidth - halfWidth, newHeight), resultPreview.PixelFormat); graphics.DrawImage(originalPreview, 0, 0, newWidth, newHeight); // First half graphics.DrawImage(croppedOutput, halfWidth, 0); // Second half graphics.FillRectangle(new SolidBrush(Color.FromArgb(192, Color.Black)), halfWidth - 2, 0, 4, newHeight); // Line Bitmap Bmp = new Bitmap(newWidth, footerHeight); Color color = Color.FromArgb(22, 22, 22); using (Graphics gfx = Graphics.FromImage(Bmp)) using (SolidBrush brush = new SolidBrush(color)) { gfx.FillRectangle(brush, 0, 0, newWidth, footerHeight); } graphics.DrawImage(Bmp, 0, newHeight); GraphicsPath p = new GraphicsPath(); int fontSize = 19; SizeF s = new Size(999999999, 99999999); Font font = new Font("Times New Roman", graphics.DpiY * fontSize / 72); string barString = "[CS] " + Path.GetFileName(Program.lastFilename) + " - " + modelName; int cf = 0, lf = 0; while (s.Width >= newWidth) { fontSize--; font = new Font(FontFamily.GenericSansSerif, graphics.DpiY * fontSize / 72, FontStyle.Regular); s = graphics.MeasureString(barString, font, new SizeF(), new StringFormat(), out cf, out lf); } StringFormat stringFormat = new StringFormat(); stringFormat.Alignment = StringAlignment.Center; double a = graphics.DpiY * fontSize / 72; stringFormat.LineAlignment = StringAlignment.Center; double contrastW = GetColorContrast(color, Color.White); double contrastB = GetColorContrast(color, Color.Black); Brush textBrush = contrastW < 3.0 ? Brushes.Black : Brushes.White; graphics.DrawString( $"{barString}", font, textBrush, new Rectangle(0, newHeight, newWidth, footerHeight - 0), stringFormat); } try { if (saveToFile) { await SaveComparisonToFile(outputImage); } else { Clipboard.SetDataObject(outputImage); } } catch { Program.ShowMessage("Failed to save comparison.", "Error"); } }
static void MergeScrollable() { if (offsetX < 0f) { offsetX *= -1f; } if (offsetY < 0f) { offsetY *= -1f; } int scale = GetScale(); offsetX *= scale; offsetY *= scale; Logger.Log("[Merger] Merging " + Path.GetFileName(outputCutoutPath) + " onto original using offset " + offsetX + "x" + offsetY); Image image = MergeInMemory(scale); MainUIHelper.currentOriginal = ImgUtils.GetImage(Paths.tempImgPath); MainUIHelper.currentOutput = image; MainUIHelper.currentScale = ImgUtils.GetScaleFloat(ImgUtils.GetImage(inputCutoutPath), ImgUtils.GetImage(outputCutoutPath)); UIHelpers.ReplaceImageAtSameScale(MainUIHelper.previewImg, image); Program.mainForm.SetProgress(0f, "Done."); }
//public static bool cacheTiling = false; public static async Task DoUpscale(string inpath, string outpath, ModelData mdl, bool cacheSplitDepth, bool alpha, PreviewMode mode, Backend backend, bool showTileProgress = true) { Program.cancelled = false; // Reset cancel flag try { if (backend == Backend.NCNN) { Program.lastModelName = mdl.model1Name; await RunNcnn(inpath, outpath, mdl.model1Path); } else { Program.mainForm.SetProgress(2f, "Starting ESRGAN..."); File.Delete(Paths.progressLogfile); string modelArg = GetModelArg(mdl); await RunJoey(inpath, outpath, modelArg, cacheSplitDepth, alpha, showTileProgress); } if (mode == PreviewMode.Cutout) { await ScalePreviewOutput(); Program.mainForm.SetProgress(100f, "Merging into preview..."); await Program.PutTaskDelay(); PreviewMerger.Merge(); Program.mainForm.SetHasPreview(true); } if (mode == PreviewMode.FullImage) { await ScalePreviewOutput(); Program.mainForm.SetProgress(100f, "Merging into preview..."); await Program.PutTaskDelay(); Image outImg = ImgUtils.GetImage(Directory.GetFiles(Paths.previewOutPath, "preview.*", SearchOption.AllDirectories)[0]); Image inputImg = ImgUtils.GetImage(Paths.tempImgPath); PreviewUI.previewImg.Image = outImg; PreviewUI.currentOriginal = inputImg; PreviewUI.currentOutput = outImg; PreviewUI.currentScale = ImgUtils.GetScaleFloat(inputImg, outImg); PreviewUI.previewImg.ZoomToFit(); Program.mainForm.SetHasPreview(true); //Program.mainForm.SetProgress(0f, "Done."); } } catch (Exception e) { Program.mainForm.SetProgress(0f, "Cancelled."); if (Program.cancelled) { return; } if (e.Message.Contains("No such file")) { Program.ShowMessage("An error occured during upscaling.\nThe upscale process seems to have exited before completion!", "Error"); } else { Program.ShowMessage("An error occured during upscaling.", "Error"); } Logger.Log("[ESRGAN] Upscaling Error: " + e.Message + "\n" + e.StackTrace); } }
public List <Point> ProcessImage(int maxEncounters = 1) { List <Point> points = new List <Point>(); int encounters = 0; PointGroup pointGroup = group.OffsetCopy(0, 0); LockBitmap lockB = ImgUtils.GetLockBitmap(rect); lockB.LockBits(); Point fartherDownRight = GetFartherPoint(); int x = 0; while (encounters < maxEncounters && (fartherDownRight.X + x) < lockB.Width) { int y = 0; while (encounters < maxEncounters && (fartherDownRight.Y + y) < lockB.Height) { bool valid = true; foreach (var pointDiff in pointDiffs) { Point p1 = GetCorrespondingPoint(pointGroup, pointDiff.Key.Item1, x, y); Point p2 = GetCorrespondingPoint(pointGroup, pointDiff.Key.Item2, x, y); Color c1 = lockB.GetPixel(p1.X, p1.Y); Color c2 = lockB.GetPixel(p2.X, p2.Y); int diff = ColorUtils.ColorDiff(c1, c2); if (diff != pointDiff.Value) { valid = false; break; } } if (valid) // Check color diffs { foreach (var colorDiff in colorDiffs) { foreach (var point in pointGroup.Points) { Point relative = new Point(point.X - x, point.Y - y); if (relative == colorDiff.Key.Item1) { int diff = ColorUtils.ColorDiff(lockB.GetPixel(point.X, point.Y), colorDiff.Key.Item2); if (diff != colorDiff.Value) { valid = false; break; } } } } } if (valid) { encounters++; points.Add(new Point(rect.X + x, rect.Y + y)); } pointGroup.OffsetY(1); ++y; } pointGroup.Offset(1, -y); ++x; } lockB.UnlockBits(); return(points); }
public static void CreateFriendlyImages(int productid, string lang) { var objCtrl = new NBrightBuyController(); var imgList = new List <string>(); var productData = new ProductData(productid, lang); var productImgFolder = StoreSettings.Current.FolderImagesMapPath.TrimEnd('\\') + "\\" + productData.DataRecord.ItemID + "\\" + lang; Utils.CreateFolder(productImgFolder); foreach (var i in productData.Imgs) { //becuase of updates to sort order and alt text we NEED to delete the existing files. Utils.DeleteSysFile(i.GetXmlProperty("genxml/lang/genxml/hidden/fimagepath")); } var lp = 1; foreach (var i in productData.Imgs) { // use imageref to link langauges var imageref = i.GetXmlProperty("genxml/hidden/imageref"); if (imageref == "") { imageref = Utils.GetUniqueKey(); productData.DataRecord.SetXmlProperty("genxml/imgs/genxml[" + lp + "]/hidden/imageref", imageref); } var imgname = i.GetXmlProperty("genxml/lang/genxml/textbox/txtimagedesc"); if (imgname == "") { imgname = productData.ProductName; } if (imgname == "") { imgname = productData.ProductRef; } if (imgname != "") { var fullName = i.GetXmlProperty("genxml/hidden/imagepath"); var extension = Path.GetExtension(fullName); imgname = AlphaNumeric(CleanFileName(imgname.Replace(" ", "-"))); var imgnameext = imgname + extension; var newImageFileName = productImgFolder + "\\" + imgnameext; var lp2 = 1; while (File.Exists(newImageFileName)) { imgnameext = imgname + "-" + lp2 + extension; newImageFileName = productImgFolder + "\\" + imgnameext; lp2++; } var imgSize = StoreSettings.Current.GetInt(StoreSettingKeys.productimageresize); if (imgSize == 0) { imgSize = 960; } if (extension != null && extension.ToLower() == ".png") { newImageFileName = ImgUtils.ResizeImageToPng(fullName, newImageFileName, imgSize); } else { newImageFileName = ImgUtils.ResizeImageToJpg(fullName, newImageFileName, imgSize); } var newimageurl = StoreSettings.Current.FolderImages.TrimEnd('/') + "/" + productData.DataRecord.ItemID + "/" + lang + "/" + imgnameext; productData.DataLangRecord.SetXmlProperty("genxml/imgs/genxml[" + lp + "]/hidden/fimageurl", newimageurl); productData.DataLangRecord.SetXmlProperty("genxml/imgs/genxml[" + lp + "]/hidden/fimagepath", newImageFileName); productData.DataLangRecord.SetXmlProperty("genxml/imgs/genxml[" + lp + "]/hidden/fimageref", imageref); imgList.Add(newImageFileName); } lp += 1; } objCtrl.Update(productData.DataLangRecord); objCtrl.Update(productData.DataRecord); // remove any deleted images. var fl = Directory.GetFiles(productImgFolder); foreach (var f in fl) { if (!imgList.Contains(f)) { Utils.DeleteSysFile(f); } } // sort other language foreach (var l in DnnUtils.GetCultureCodeList()) { if (l != lang) { var strXml = ""; var pData = new ProductData(productid, l); var lp3 = 1; foreach (var langimg in pData.Imgs) { var imgref = langimg.GetXmlProperty("genxml/hidden/imageref"); var strNode = pData.DataLangRecord.GetXmlNode("genxml/imgs/genxml[./hidden/fimageref='" + imgref + "']"); if (strNode == "") { // create missing ref and get xml. (May misalign images alts) pData.DataLangRecord.SetXmlProperty("genxml/imgs/genxml[" + lp3 + "]/hidden/fimageref", imgref); strNode = pData.DataLangRecord.GetXmlNode("genxml/imgs/genxml[./hidden/fimageref='" + imgref + "']"); } strXml += "<genxml>" + strNode + "</genxml>"; lp3 += 1; } strXml = "<imgs>" + strXml + "</imgs>"; pData.DataLangRecord.RemoveXmlNode("genxml/imgs"); pData.DataLangRecord.AddXmlNode(strXml, "imgs", "genxml"); objCtrl.Update(pData.DataLangRecord); } } RemoveProductDataCache(PortalSettings.Current.PortalId, productid); }
public static async Task DoUpscale(string inpath, string outpath, ModelData mdl, string tilesize, bool alpha, PreviewMode mode, Backend backend, bool showTileProgress = true) { bool useJoey = Config.GetInt("esrganVer") == 0; try { if (backend == Backend.NCNN) { Program.mainForm.SetProgress(1f, "Loading ESRGAN-NCNN..."); DialogForm dialogForm = new DialogForm("Loading ESRGAN-NCNN...\nThis should take 10-25 seconds.", 14); Program.lastModelName = mdl.model1Name; await RunNcnn(inpath, outpath, mdl.model1Path); } else { Program.mainForm.SetProgress(4f, "Starting ESRGAN..."); File.Delete(Paths.progressLogfile); string modelArg = GetModelArg(mdl, useJoey); if (useJoey) { await RunJoey(inpath, outpath, modelArg, tilesize, alpha, showTileProgress); } else { await Run(inpath, outpath, modelArg, tilesize, alpha, showTileProgress); } } if (mode == PreviewMode.Cutout) { await ScalePreviewOutput(); Program.mainForm.SetProgress(100f, "Merging into preview..."); await Program.PutTaskDelay(); PreviewMerger.Merge(); Program.mainForm.SetHasPreview(true); } if (mode == PreviewMode.FullImage) { await ScalePreviewOutput(); Program.mainForm.SetProgress(100f, "Merging into preview..."); await Program.PutTaskDelay(); Image outImg = ImgUtils.GetImage(Directory.GetFiles(Paths.previewOutPath, "*.png.*", SearchOption.AllDirectories)[0]); Image inputImg = ImgUtils.GetImage(Paths.tempImgPath); MainUIHelper.previewImg.Image = outImg; MainUIHelper.currentOriginal = inputImg; MainUIHelper.currentOutput = outImg; MainUIHelper.currentScale = ImgUtils.GetScaleFloat(inputImg, outImg); MainUIHelper.previewImg.ZoomToFit(); Program.mainForm.SetHasPreview(true); //Program.mainForm.SetProgress(0f, "Done."); } } catch (Exception e) { if (e.Message.Contains("No such file")) { Program.ShowMessage("An error occured during upscaling.\nThe upscale process seems to have exited before completion!", "Error"); } else { Program.ShowMessage("An error occured during upscaling.", "Error"); } Logger.Log("[ESRGAN] Upscaling Error: " + e.Message + "\n" + e.StackTrace); Program.mainForm.SetProgress(0f, "Cancelled."); } }
public FormColorMain() { InitializeComponent(); btnFindToolTip = new ToolTip(); ImgUtils.Init(); }
/// <summary> /// Thumbnail image /// </summary> /// <param name="info">NBrightInfo class of PRD type</param> /// <param name="width">width</param> /// <param name="height">height</param> /// <param name="idx">index of the image to display</param> /// <param name="attributes">free text added onto end of url parameters</param> /// <returns>Thumbnailer url</returns> public IEncodedString ProductImage(NBrightInfo info, string width = "150", string height = "0", string idx = "1", string attributes = "", bool fileImage = false, bool outputPNG = false) { var url = ""; var imageurlsrc = info.GetXmlProperty("genxml/imgs/genxml[" + idx + "]/hidden/imageurl"); if (fileImage) { var src = HttpContext.Current.Server.MapPath(imageurlsrc); var strCacheKey = info.PortalId + "*" + src + "*" + Utils.GetCurrentCulture() + "*imgfile:" + width + "*" + height + "*"; url = (String)Utils.GetCache(strCacheKey); if (String.IsNullOrEmpty(url)) { var imgpath = Path.GetFileNameWithoutExtension(src); var ext = ".jpg"; if (outputPNG) { ext = ".png"; } var thumbname = imgpath + "_Thumb" + width + "x" + height + ext; imgpath = Path.GetFullPath(src).Replace(Path.GetFileName(src), "") + thumbname; url = imageurlsrc.Replace(Path.GetFileName(src), thumbname); if (!File.Exists(imgpath)) { var newImage = ImgUtils.CreateThumbnail(src, Convert.ToInt32(width), Convert.ToInt32(height)); ImageCodecInfo useEncoder; useEncoder = ImgUtils.GetEncoder(ImageFormat.Jpeg); if (outputPNG) { useEncoder = ImgUtils.GetEncoder(ImageFormat.Png); } var encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85L); try { newImage.Save(imgpath, useEncoder, encoderParameters); } catch (Exception exc) { if (StoreSettings.Current.DebugMode) { url = exc.ToString(); } } } if (!StoreSettings.Current.DebugMode) { Utils.SetCache(strCacheKey, url); } } } else { url = StoreSettings.NBrightBuyPath() + "/NBrightThumb.ashx?src=" + imageurlsrc + "&w=" + width + "&h=" + height + attributes; } return(new RawString(url)); }