private void SaveWindow_Click(object sender, RoutedEventArgs e) { var tab = Canvases.SelectedItem as TabItem; var usercntr = tab.Content as Controls.canvasSurface; var canvas = usercntr.Crtanje; RenderTargetBitmap rtb = new RenderTargetBitmap((int)canvas.ActualWidth, (int)canvas.ActualHeight, 96d, 96d, System.Windows.Media.PixelFormats.Default); rtb.Render(canvas); BitmapFrame frame = BitmapFrame.Create(rtb); var encoder = new BmpBitmapEncoder(); encoder.Frames.Add(frame); System.IO.MemoryStream ms = new System.IO.MemoryStream(); encoder.Save(ms); ms.Close(); System.IO.File.WriteAllBytes(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop) + "\\" + tab.Header.ToString() + ".bmp", ms.ToArray()); Confirmation_form confirm = new Confirmation_form(); confirm.Show(); }
/* * Offset (hex) Offset (dec) Size (bytes) Windows BITMAPINFOHEADER[1] * 0E 14 4 the size of this header (40 bytes) * 12 18 4 the bitmap width in pixels (signed integer) * 16 22 4 the bitmap height in pixels (signed integer) * 1A 26 2 the number of color planes (must be 1) * 1C 28 2 the number of bits per pixel, which is the color depth of the image. Typical values are 1, 4, 8, 16, 24 and 32. * 1E 30 4 the compression method being used. See the next table for a list of possible values * 22 34 4 the image size. This is the size of the raw bitmap data; a dummy 0 can be given for BI_RGB bitmaps. * 26 38 4 the horizontal resolution of the image. (pixel per meter, signed integer) * 2A 42 4 the vertical resolution of the image. (pixel per meter, signed integer) * 2E 46 4 the number of colors in the color palette, or 0 to default to 2n * 32 50 4 the number of important colors used, or 0 when every color is important; generally ignored */ byte[] SaveAsBitmap(BitmapSource bmp, bool strip_header) { var encoder = new BmpBitmapEncoder(); using (var stream = new MemoryStream()) { encoder.Frames.Add(BitmapFrame.Create(bmp)); encoder.Save(stream); var bitmap = stream.ToArray(); // skip bitmap file header int len = 14; if (strip_header) { len += 40; // sizeof BITMAPINFOHEADER } if (bitmap.Length <= len) { throw new Exception("Bitmap encoding error. Resulting buffer is too small."); } var copy = new byte[bitmap.Length - len]; Array.Copy(bitmap, len, copy, 0, copy.Length); return(copy); } }
public static void ToFile(this BitmapImage bmp, string path, ImageType imgType = ImageType.BMP) { FileInfo finfo = new FileInfo(path); BitmapEncoder encoder = null; switch (imgType) { case ImageType.JPG: encoder = new JpegBitmapEncoder(); break; case ImageType.PNG: encoder = new PngBitmapEncoder(); break; default: encoder = new BmpBitmapEncoder(); break; } encoder.Frames.Add(BitmapFrame.Create(bmp)); using (var filestream = finfo.Create()) encoder.Save(filestream); }
private void RenderFourierTransform() { XMLNode node = navPage.metaTab.Nodes.Find(x => x.Name == "svg"); int width = (int)navPage.imageTab.SVGImage.ActualWidth; int height = (int)navPage.imageTab.SVGImage.ActualHeight; var renderBitmap = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32); var visualBrush = new VisualBrush { Visual = navPage.imageTab.SVGImage, Stretch = Stretch.Uniform }; System.Windows.Size size = new System.Windows.Size(width, height); var drawingvisual = new DrawingVisual(); using (var context = drawingvisual.RenderOpen()) { context.DrawRectangle(visualBrush, null, new Rect(size)); } renderBitmap.Render(drawingvisual); MemoryStream stream = new MemoryStream(); BitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); encoder.Save(stream); Bitmap bitmap = new Bitmap(stream); bitmap = ImageProcessing.AddPadding(bitmap); PaddingImageControl.Source = ImageProcessing.ToBitmapImage(bitmap); MagnitudeImageControl.Source = ImageProcessing.MakeFFTMagnitude(bitmap); PhaseImageControl.Source = ImageProcessing.MakeFFTPhase(bitmap); }
public static void ToBmpFile(this BitmapSource source, string filePath) { if (null == source || string.IsNullOrEmpty(filePath)) { return; } var bmpBitmapEncoder = new BmpBitmapEncoder(); bmpBitmapEncoder.Frames.Add(BitmapFrame.Create(source)); try { using (var stream = File.Create(filePath)) { bmpBitmapEncoder.Save(stream); } } catch (Exception ex) { //Log.GetLogger.Info(ex.Message); Application.Current.GetLocator().Main.log.Error(ex.Message); } }
private void Print2DIDs() { string[] plots = new string[] { "MxMy", "MxN", "MyN" }; foreach (var p in plots) { var pngExporter = new OxyPlot.Wpf.PngExporter { Width = 600, Height = 400, Background = OxyColors.White }; var bitmap = pngExporter.ExportToBitmap(this.GetType().GetProperty(p + "ID").GetValue(this) as PlotModel); MemoryStream stream = new MemoryStream(); BitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap)); encoder.Save(stream); Bitmap bmp = new Bitmap(stream); ImageConverter converter = new ImageConverter(); byte[] output = (byte[])converter.ConvertTo(bmp, typeof(byte[])); string path = System.IO.Path.GetTempPath() + p + ".tmp"; File.WriteAllBytes(path, output); } }
public static byte[] BitmapToByteArray(object img, string fileName) { using (var stream = new MemoryStream()) { BitmapEncoder encoder; switch (Path.GetExtension(fileName).ToLower()) { case ".jpg": case ".jpeg": encoder = new JpegBitmapEncoder(); break; case ".png": encoder = new PngBitmapEncoder(); break; case ".bmp": encoder = new BmpBitmapEncoder(); break; case ".gif": encoder = new GifBitmapEncoder(); break; case ".tiff": encoder = new TiffBitmapEncoder(); break; default: throw new EncoderFallbackException("Неизвестный формат файла изображения. Подерживаемые форматы изображений: jpeg, png, bmp, gif и tiff."); } encoder.Frames.Add(BitmapFrame.Create((BitmapSource)img)); encoder.Save(stream); return(stream.ToArray()); } }
private Bitmap GetHandWrittenImage() { RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)inkCanvas.ActualWidth, (int)inkCanvas.ActualHeight, 96d, 96d, PixelFormats.Default); renderBitmap.Render(inkCanvas); BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); Bitmap bitmap; using (MemoryStream ms = new MemoryStream()) { encoder.Save(ms); ms.Flush(); //get the bitmap bytes from the memory stream ms.Position = 0; bitmap = new Bitmap(Image.FromStream(ms)); } return(bitmap); }
// Returns a BitmapEncoder corresponding to a given imageContentType private static BitmapEncoder GetBitmapEncoder(string imageContentType) { BitmapEncoder bitmapEncoder; switch (imageContentType) { case ImageBmpContentType: bitmapEncoder = new BmpBitmapEncoder(); break; case ImageGifContentType: bitmapEncoder = new GifBitmapEncoder(); break; case ImageJpegContentType: bitmapEncoder = new JpegBitmapEncoder(); // break; case ImageTiffContentType: bitmapEncoder = new TiffBitmapEncoder(); break; case ImagePngContentType: bitmapEncoder = new PngBitmapEncoder(); break; default: Invariant.Assert(false, "Unexpected image content type: " + imageContentType); bitmapEncoder = null; break; } return(bitmapEncoder); }
/// <summary> /// Takes a byte array containing heights in coordinant space and returns them output as a bitmap image. /// NOTE: this method will only work for byte arrays where the width and height are equal lengths. /// </summary> /// <param name="bytes">Array of bytes to be converted into a bitmap, this is normally the output form <see cref="LatticeNoiseGenerator"/></param> /// <returns>A bitmap image</returns> public static Bitmap Convert(byte[] bytes) { int size = (int)Math.Sqrt(bytes.Length); int pixelIndex = 0; byte[] pixels = new byte[size * size * 4]; for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { byte pixelRGB = bytes[x + y * size]; for (int i = 0; i < 3; i++) { pixels[pixelIndex++] = pixelRGB; } pixels[pixelIndex++] = 255; } } WriteableBitmap bitmap = new WriteableBitmap(size, size, 96, 96, PixelFormats.Bgr32, null); Int32Rect rect = new Int32Rect(0, 0, size, size); bitmap.WritePixels(rect, pixels, size * 4, 0); using (MemoryStream stream = new MemoryStream()) { BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create((BitmapSource)bitmap)); encoder.Save(stream); return(new Bitmap(stream)); } }
public static byte[] BitmapSourceToBytes(BitmapSource image) { byte[] data = new byte[] { }; if (image != null) { try { var encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(image)); using (MemoryStream ms = new MemoryStream()) { encoder.Save(ms); data = ms.ToArray(); } return(data); } catch (Exception ex) { Log.Error(ex, "Error'"); } } return(data); }
private void DepthFrameReader_FrameArrived(object sender, DepthFrameArrivedEventArgs e) { if (NameInserted == true && ImageCount < 6) { string path = "C:/Users/CPT Danko/Desktop/images/" + label + index + "_" + ImageCount.ToString() + ".png"; var Gray8DepthBmp = new FormatConvertedBitmap(((MainWindow)Application.Current.MainWindow).depthbitmap, PixelFormats.Gray8, null, 0d); // - create a new formated bitmap for saving the image to the file var encoder = new BmpBitmapEncoder(); // - create an encoder for converting to a bmp file encoder.Frames.Add(BitmapFrame.Create(Gray8DepthBmp)); // - adds a frame with the speciefied format to the encoder using (var fileStream = new FileStream(path, FileMode.Create)) { encoder.Save(fileStream); // - save the file to the defined path from the encoder } ImageCount++; } else if (ImageCount > 5) { this.Close(); } }
/// <summary> /// 저장 포맷에 맞게 비트맵을 인코딩 후 저장합니다. /// </summary> /// <param name="source"></param> public static void Save(BitmapSource source, bool png) { var strFileName = "Test.jpg"; FileStream stream = new FileStream(strFileName, FileMode.Create, FileAccess.Write); BitmapEncoder encoder = new PngBitmapEncoder(); strFileName.ToCharArray(strFileName.Length - 3, 3); string upper = strFileName.ToUpper(); char[] format = upper.ToCharArray(strFileName.Length - 3, 3); upper = new string(format); if (!png) { switch (upper.ToString()) { case "JPG": encoder = new JpegBitmapEncoder(); break; case "GIF": encoder = new GifBitmapEncoder(); break; case "BMP": encoder = new BmpBitmapEncoder(); break; } } encoder.Frames.Add(BitmapFrame.Create(source)); encoder.Save(stream); stream.Close(); }
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { foreach (var kv in cachedBitmaps) { if (kv.Value == value) { return(kv.Key); } } Bitmap bitmap; using (MemoryStream outStream = new MemoryStream()) { BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(value as BitmapSource)); enc.Save(outStream); outStream.Position = 0; bitmap = new Bitmap(outStream); } return(bitmap); }
// Get a bitmap from the given data (either BitmapSource or Bitmap) /// <SecurityNote> /// Critical: This code returns a handle to an unmanaged object /// </SecurityNote> private static Bitmap GetBitmapImpl(object data) { BitmapSource bitmapSource = data as BitmapSource; if (bitmapSource != null) { // Convert BitmapSource to System.Drawing.Bitmap to get Win32 HBITMAP. BitmapEncoder bitmapEncoder; Stream bitmapStream; bitmapEncoder = new BmpBitmapEncoder(); bitmapEncoder.Frames.Add(BitmapFrame.Create(bitmapSource)); bitmapStream = new MemoryStream(); bitmapEncoder.Save(bitmapStream); return(new Bitmap(bitmapStream)); } else { // Get Bitmap data from data object. return(data as Bitmap); } }
public void InvertImage() { Thickness margin = canvas.Margin; canvas.Margin = new Thickness(0); RenderTargetBitmap rtb = CanvasToBitmap(); canvas.Margin = margin; System.Drawing.Bitmap bitmap; try { System.IO.MemoryStream ms = new System.IO.MemoryStream(); //Создаем поток в память. BitmapEncoder bmpEncoder = new BmpBitmapEncoder(); bmpEncoder.Frames.Add(BitmapFrame.Create(rtb)); bmpEncoder.Save(ms); bitmap = new System.Drawing.Bitmap(ms); ms.Close(); bckGrWorker.RunWorkerAsync(bitmap); } catch (Exception ex) { System.Windows.MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
internal void SaveButton_Click(object sender, RoutedEventArgs e) { var basePath = Path.GetDirectoryName(GetType().Assembly.Location); while (!Directory.Exists(Path.Combine(basePath, "Result"))) { basePath = Path.GetDirectoryName(basePath); } var viewModel = (TestViewModel)DataContext; var fileName = Path.Combine(basePath, "Result", $"{viewModel.Platform}.{viewModel.Name}.png"); App.Root.ViewModel.Status = $"Saving {fileName}..."; var frame = BitmapFrame.Create(CreateBitmap()); var encoder = new BmpBitmapEncoder(); encoder.Frames.Add(frame); using (var stream = File.Create(fileName)) encoder.Save(stream); App.Root.ViewModel.Status = ""; }
public static async Task <UwpSoftwareBitmap> ConvertFrom(BitmapFrame sourceBitmap) { // BitmapFrameをBMP形式のバイト配列に変換 byte[] bitmapBytes; var encoder = new BmpBitmapEncoder(); // ここは.NET用のエンコーダーを使う encoder.Frames.Add(sourceBitmap); using (var memoryStream = new MemoryStream()) { encoder.Save(memoryStream); bitmapBytes = memoryStream.ToArray(); } // バイト配列をUWPのIRandomAccessStreamに変換 using (var randomAccessStream = new UwpInMemoryRandomAccessStream()) { using (var outputStream = randomAccessStream.GetOutputStreamAt(0)) using (var writer = new UwpDataWriter(outputStream)) { writer.WriteBytes(bitmapBytes); await writer.StoreAsync(); await outputStream.FlushAsync(); } // IRandomAccessStreamをSoftwareBitmapに変換 // (ここはUWP APIのデコーダーを使う) var decoder = await UwpBitmapDecoder.CreateAsync(randomAccessStream); var softwareBitmap = await decoder.GetSoftwareBitmapAsync(UwpBitmapPixelFormat.Bgra8, UwpBitmapAlphaMode.Premultiplied); return(softwareBitmap); } }
private void BackgroundFileSave(object state) { var job = state as SaveImageJob; lock (this.imageSync) { if (job.UpdateVersion < updateVersion) { return; } } lock (job.ImageFileSync) { try { using (var memoryStream = new MemoryStream()) { // Write the bitmap out to a memory stream before saving so that we won't be holding // a write lock on the BitmapImage for very long; it's used in the UI. var encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(job.Image)); encoder.Save(memoryStream); using (var fileStream = new FileStream(job.FilePath, FileMode.Create)) { fileStream.Write(memoryStream.GetBuffer(), 0, (int)memoryStream.Length); } } } catch (IOException) { // Directory may have been deleted. Ignore. } } }
// Returns a BitmapEncoder corresponding to a given imageContentType private static BitmapEncoder GetBitmapEncoder(string imageContentType) { BitmapEncoder bitmapEncoder; switch (imageContentType) { case ImageBmpContentType: bitmapEncoder = new BmpBitmapEncoder(); break; case ImageGifContentType: bitmapEncoder = new GifBitmapEncoder(); break; case ImageJpegContentType: bitmapEncoder = new JpegBitmapEncoder(); // investigate crash when qualitylevel is set to 100. //((JpegBitmapEncoder)bitmapEncoder).QualityLevel = 100; // To minimize data loss; default is 75 break; case ImageTiffContentType: bitmapEncoder = new TiffBitmapEncoder(); break; case ImagePngContentType: bitmapEncoder = new PngBitmapEncoder(); break; default: Invariant.Assert(false, "Unexpected image content type: " + imageContentType); bitmapEncoder = null; break; } return(bitmapEncoder); }
private static BitmapImage ConvertRenderTargetBitmapToBitmapImage(RenderTargetBitmap inputRTB) { // converts a RenderTargetBitmap to BitmapImage // from http://stackoverflow.com/questions/13987408/convert-rendertargetbitmap-to-bitmapimage // see also http://stackoverflow.com/questions/20083210/convert-rendertargetbitmap-to-bitmap?rq=1 var bitmapImage = new BitmapImage(); //var bitmapEncoder = new PngBitmapEncoder(); var bitmapEncoder = new BmpBitmapEncoder(); // BMP instead of PNG - no need for transparency bitmapEncoder.Frames.Add(BitmapFrame.Create(inputRTB)); using (var stream = new MemoryStream()) { bitmapEncoder.Save(stream); stream.Seek(0, SeekOrigin.Begin); bitmapImage.BeginInit(); bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.StreamSource = stream; bitmapImage.EndInit(); } return(bitmapImage); }
public static Bitmap ConvertBitmapImageToBitmap(BitmapImage bitmapImage) { using (MemoryStream outStream = new MemoryStream() { Position = 0 }) { BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(bitmapImage.CloneCurrentValue())); enc.Save(outStream); System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream); return(new Bitmap(bitmap)); } /*try * { * return new Bitmap(bitmapImage.StreamSource); * } * catch * { * return (Bitmap)(Bitmap.FromFile(bitmapImage.UriSource.AbsolutePath)); * }*/ }
private void Save_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.SaveFileDialog dlgSave = new Microsoft.Win32.SaveFileDialog(); dlgSave.FileName = "MultitoolPaintImage"; // Имя файла по умолчанию dlgSave.DefaultExt = ".jpg"; // Формат файса по умолчанию dlgSave.Filter = "Image (.jpg)|*.jpg"; // Фильтр доступных расширений Nullable <bool> result = dlgSave.ShowDialog(); // Вывод окна сохранения на экран if (result == true) { // Save document string filename = dlgSave.FileName;// Сохранение файла //Получаем размеры элемента InkCanvas int margin = (int)this.PaintCanvas.Margin.Left; int width = (int)this.PaintCanvas.Width - margin; int height = (int)this.PaintCanvas.Height - margin; //Переводим содержимое InkCanvas в растровое изображение RenderTargetBitmap rtb = new RenderTargetBitmap(width, height, 96d, 96d, PixelFormats.Default); DrawingVisual drawingVisual = new DrawingVisual(); using (DrawingContext drawingContext = drawingVisual.RenderOpen()) { VisualBrush visualBrush = new VisualBrush(PaintCanvas); drawingContext.DrawRectangle(visualBrush, null, new Rect(new Point(0, 0), new Size(width, height))); } rtb.Render(drawingVisual); //Сохраняем изображение using (FileStream savestream = new FileStream(filename, FileMode.Create)) { BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(rtb)); encoder.Save(savestream); } } }
/// <summary> /// Show Image for Copy & Paste /// </summary> private void ShowImage(BitmapSource source) { projectName.Text = "MyProject"; fileName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\MyProject"; using (var memoryStream = new MemoryStream()) { imageSource = new BitmapImage(); var encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(source)); encoder.Save(memoryStream); imageSource.BeginInit(); imageSource.StreamSource = new MemoryStream(memoryStream.ToArray()); imageSource.EndInit(); } grayImage.Source = imageSource; var isSmallerThan800X600 = IsImageSmallerThan800X600(imageSource); grayImage.Width = isSmallerThan800X600 ? imageSource.PixelWidth : 800; grayImage.Height = isSmallerThan800X600 ? imageSource.PixelHeight : 600; NewImageDisplayed(); }
private BitmapEncoder GetEncoderByExtension(string fileName) { var extension = Path.GetExtension(fileName).Trim().ToLower(); BitmapEncoder encoder; if (extension == ".jpg" || extension == ".jpeg") { encoder = new JpegBitmapEncoder(); } else if (extension == ".bmp") { encoder = new BmpBitmapEncoder(); } else if (extension == ".png") { encoder = new PngBitmapEncoder(); } else { throw new IOException($"File can not be saved in *{extension} extension"); } return(encoder); }
public static string JoinImage(string[] images, int width, int height) { System.Drawing.Bitmap[] imageFiles = new System.Drawing.Bitmap[images.Length]; for (int i = 0; i < imageFiles.Length; i++) { BitmapImage img = new BitmapImage(new Uri(images[i], UriKind.RelativeOrAbsolute)); System.IO.MemoryStream ms = new System.IO.MemoryStream(); BmpBitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create((BitmapSource)img)); encoder.Save(ms); imageFiles[i] = new System.Drawing.Bitmap(ms); ms.Close(); } string directory = SDKClient.SDKClient.Instance.property.CurrentAccount.facePath; int currentHeight = 0; int currentWidth = 0; if (imageFiles.Length > 9) { Bitmap source9 = new Bitmap(width, height); Graphics graph9 = Graphics.FromImage(source9); graph9.SmoothingMode = SmoothingMode.AntiAlias; graph9.Clear(System.Drawing.Color.White); graph9.DrawImage(source9, width, height); for (int i = 0; i < 9; i++) { Bitmap desc9 = new Bitmap(imageFiles[i], (width - 2) / 3, (height - 2) / 3); currentWidth = desc9.Width; currentHeight = desc9.Height; switch (i) { case 0: graph9.DrawImage(desc9, 0, 0); desc9.Dispose(); break; case 1: graph9.DrawImage(desc9, currentWidth + 1, 0); desc9.Dispose(); break; case 2: graph9.DrawImage(desc9, 2 * (currentWidth + 1), 0); desc9.Dispose(); break; case 3: graph9.DrawImage(desc9, 0, currentHeight + 1); desc9.Dispose(); break; case 4: graph9.DrawImage(desc9, currentWidth + 1, currentHeight + 1); desc9.Dispose(); break; case 5: graph9.DrawImage(desc9, 2 * (currentWidth + 1), currentHeight + 1); desc9.Dispose(); break; case 6: graph9.DrawImage(desc9, 0, 2 * (currentHeight + 1)); desc9.Dispose(); break; case 7: graph9.DrawImage(desc9, currentWidth + 1, 2 * (currentHeight + 1)); desc9.Dispose(); break; case 8: graph9.DrawImage(desc9, 2 * (currentWidth + 1), 2 * (currentHeight + 1)); desc9.Dispose(); break; } } graph9.Dispose(); //source9.Save(fileName); directory = CreateImage(directory, source9); } else { switch (imageFiles.Length) { case 3: Bitmap source3 = new Bitmap(width + 1, height + 1); Graphics graph3 = Graphics.FromImage(source3); graph3.SmoothingMode = SmoothingMode.AntiAlias; graph3.Clear(System.Drawing.Color.White); graph3.DrawImage(source3, width, height); for (int i = 0; i < imageFiles.Length; i++) { Bitmap desc3 = new Bitmap(imageFiles[i], width, height); currentWidth = desc3.Width; currentHeight = desc3.Height; switch (i) { case 0: graph3.DrawImage(desc3, 0, -((currentHeight / 2) + 1)); break; case 1: graph3.DrawImage(desc3, -((currentWidth / 2) + 1), (currentHeight / 2) + 1); break; case 2: graph3.DrawImage(desc3, (currentWidth / 2) + 1, (currentHeight / 2) + 1); break; } desc3.Dispose(); } graph3.Dispose(); directory = CreateImage(directory, source3); // source3.Save(fileName); break; case 4: Bitmap source4 = new Bitmap(width, height); Graphics graph4 = Graphics.FromImage(source4); graph4.SmoothingMode = SmoothingMode.AntiAlias; graph4.Clear(System.Drawing.Color.White); graph4.DrawImage(source4, width, height); for (int i = 0; i < imageFiles.Length; i++) { Bitmap desc4 = new Bitmap(imageFiles[i], width / 2 - 1, height / 2 - 1); currentWidth = desc4.Width; currentHeight = desc4.Height; switch (i) { case 0: graph4.DrawImage(desc4, 0, 0); desc4.Dispose(); break; case 1: graph4.DrawImage(desc4, currentWidth + 1, 0); desc4.Dispose(); break; case 2: graph4.DrawImage(desc4, 0, currentHeight + 1); desc4.Dispose(); break; case 3: graph4.DrawImage(desc4, currentWidth + 1, currentHeight + 1); desc4.Dispose(); break; } } graph4.Dispose(); // source4.Save(fileName); directory = CreateImage(directory, source4); break; case 5: Bitmap source5 = new Bitmap(width, height); Graphics graph5 = Graphics.FromImage(source5); graph5.SmoothingMode = SmoothingMode.AntiAlias; graph5.Clear(System.Drawing.Color.White); graph5.DrawImage(source5, width, height); for (int i = 0; i < imageFiles.Length; i++) { switch (i) { case 0: Bitmap b0 = new Bitmap(imageFiles[i], (width - 1) / 2, (height - 1) / 2); graph5.DrawImage(b0, 0, 0); break; case 1: Bitmap b1 = new Bitmap(imageFiles[i], (width - 1) / 2, (height - 1) / 2); graph5.DrawImage(b1, b1.Width + 1, 0); break; case 2: Bitmap b2 = new Bitmap(imageFiles[i], (width - 2) / 3, (height - 1) / 2); graph5.DrawImage(b2, 0, b2.Height + 1); break; case 3: Bitmap b3 = new Bitmap(imageFiles[i], (width - 2) / 3, (height - 1) / 2); graph5.DrawImage(b3, b3.Width + 1, b3.Height + 1); break; case 4: Bitmap b4 = new Bitmap(imageFiles[i], (width - 2) / 3, (height - 1) / 2); graph5.DrawImage(b4, 2 * b4.Width + 2, b4.Height + 1); break; } } graph5.Dispose(); // source5.Save(fileName); directory = CreateImage(directory, source5); break; case 6: Bitmap source6 = new Bitmap(width, height); Graphics graph6 = Graphics.FromImage(source6); graph6.SmoothingMode = SmoothingMode.AntiAlias; graph6.Clear(System.Drawing.Color.White); graph6.DrawImage(source6, source6.Width, source6.Height); for (int i = 0; i < imageFiles.Length; i++) { Bitmap desc6 = new Bitmap(imageFiles[i], width / 2, height / 2); currentWidth = desc6.Width; currentHeight = desc6.Height; switch (i) { case 0: graph6.DrawImage(desc6, -(3 * currentWidth) / 6, 0); break; case 1: graph6.DrawImage(desc6, (3 * currentWidth) / 6, 0); break; case 2: graph6.DrawImage(desc6, (((3 * currentWidth) / 6)) * 3, 0); break; case 3: graph6.DrawImage(desc6, -(3 * currentWidth) / 6, currentHeight + 1); break; case 4: graph6.DrawImage(desc6, (3 * currentWidth) / 6, currentHeight + 1); break; case 5: graph6.DrawImage(desc6, (((3 * currentWidth) / 6)) * 3, currentHeight + 1); break; } desc6.Dispose(); } graph6.Dispose(); // source6.Save(fileName); directory = CreateImage(directory, source6); break; case 7: Bitmap source7 = new Bitmap(width, height); Graphics graph7 = Graphics.FromImage(source7); graph7.SmoothingMode = SmoothingMode.AntiAlias; graph7.Clear(System.Drawing.Color.White); graph7.DrawImage(source7, source7.Width, source7.Height); for (int i = 0; i < imageFiles.Length; i++) { Bitmap desc7 = new Bitmap(imageFiles[i], (width - 2) / 3, (height - 2) / 3); currentWidth = desc7.Width; currentHeight = desc7.Height; switch (i) { case 0: graph7.DrawImage(desc7, currentWidth, 0); break; case 1: graph7.DrawImage(desc7, 0, currentHeight + 1); break; case 2: graph7.DrawImage(desc7, currentWidth + 1, currentHeight + 1); break; case 3: graph7.DrawImage(desc7, 2 * (currentWidth + 1), currentHeight + 1); break; case 4: graph7.DrawImage(desc7, 0, 2 * (currentHeight + 1)); break; case 5: graph7.DrawImage(desc7, currentWidth + 1, 2 * (currentHeight + 1)); break; case 6: graph7.DrawImage(desc7, 2 * (currentWidth + 1), 2 * (currentHeight + 1)); break; } desc7.Dispose(); } graph7.Dispose(); //source7.Save(fileName); directory = CreateImage(directory, source7); break; case 8: Bitmap source8 = new Bitmap(width, height); Graphics graph8 = Graphics.FromImage(source8); graph8.SmoothingMode = SmoothingMode.AntiAlias; graph8.Clear(System.Drawing.Color.White); graph8.DrawImage(source8, source8.Width, source8.Height); for (int i = 0; i < imageFiles.Length; i++) { Bitmap desc8 = new Bitmap(imageFiles[i], (width - 2) / 3, (height - 2) / 3); currentWidth = desc8.Width; currentHeight = desc8.Height; switch (i) { case 0: graph8.DrawImage(desc8, 3 * currentWidth / 6, 0); break; case 1: graph8.DrawImage(desc8, (3 * currentWidth / 6) * 3, 0); break; case 2: graph8.DrawImage(desc8, 0, currentHeight + 1); break; case 3: graph8.DrawImage(desc8, currentWidth + 1, currentHeight + 1); break; case 4: graph8.DrawImage(desc8, 2 * (currentWidth + 1), currentHeight + 1); break; case 5: graph8.DrawImage(desc8, 0, 2 * (currentHeight + 1)); break; case 6: graph8.DrawImage(desc8, currentWidth + 1, 2 * (currentHeight + 1)); break; case 7: graph8.DrawImage(desc8, 2 * (currentWidth + 1), 2 * (currentHeight + 1)); break; } desc8.Dispose(); } graph8.Dispose(); // source8.Save(fileName); directory = CreateImage(directory, source8); break; case 9: Bitmap source9 = new Bitmap(width, height); Graphics graph9 = Graphics.FromImage(source9); graph9.SmoothingMode = SmoothingMode.AntiAlias; graph9.Clear(System.Drawing.Color.White); graph9.DrawImage(source9, width, height); for (int i = 0; i < imageFiles.Length; i++) { Bitmap desc9 = new Bitmap(imageFiles[i], (width - 2) / 3, (height - 2) / 3); currentWidth = desc9.Width; currentHeight = desc9.Height; switch (i) { case 0: graph9.DrawImage(desc9, 0, 0); desc9.Dispose(); break; case 1: graph9.DrawImage(desc9, currentWidth + 1, 0); desc9.Dispose(); break; case 2: graph9.DrawImage(desc9, 2 * (currentWidth + 1), 0); desc9.Dispose(); break; case 3: graph9.DrawImage(desc9, 0, currentHeight + 1); desc9.Dispose(); break; case 4: graph9.DrawImage(desc9, currentWidth + 1, currentHeight + 1); desc9.Dispose(); break; case 5: graph9.DrawImage(desc9, 2 * (currentWidth + 1), currentHeight + 1); desc9.Dispose(); break; case 6: graph9.DrawImage(desc9, 0, 2 * (currentHeight + 1)); desc9.Dispose(); break; case 7: graph9.DrawImage(desc9, currentWidth + 1, 2 * (currentHeight + 1)); desc9.Dispose(); break; case 8: graph9.DrawImage(desc9, 2 * (currentWidth + 1), 2 * (currentHeight + 1)); desc9.Dispose(); break; } } graph9.Dispose(); //source9.Save(fileName); directory = CreateImage(directory, source9); break; default: break; } } return(directory); }
private CustomGM3D setModel(int m) { MeshGeometry3D mg = new MeshGeometry3D(); mg.Positions = mData[m].Mesh.Vertices; mg.Indices = mData[m].Mesh.Indices; mg.Normals = mData[m].Mesh.Normals; mg.TextureCoordinates = mData[m].Mesh.TextureCoordinates; mg.Colors = mData[m].Mesh.VertexColors; mg.Tangents = new HelixToolkit.Wpf.SharpDX.Core.Vector3Collection(); MeshBuilder.ComputeTangents(mg); mg.BiTangents = mData[m].Mesh.BiTangents; mData[m].Mesh.Tangents = mg.Tangents; CustomGM3D gm3d = new CustomGM3D(); List <byte> DDS = new List <byte>(); diffuse = null; if (mData[m].Diffuse != null) { diffuse = new MemoryStream(); BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(mData[m].Diffuse)); enc.Save(diffuse); } normal = null; if (mData[m].Normal != null) { normal = new MemoryStream(); BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(mData[m].Normal)); enc.Save(normal); } specular = null; if (mData[m].Specular != null) { specular = new MemoryStream(); var enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(mData[m].Specular)); enc.Save(specular); } alpha = null; if (mData[m].Alpha != null) { alpha = new MemoryStream(); var enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(mData[m].Alpha)); enc.Save(alpha); } emissive = null; if (mData[m].Emissive != null) { emissive = new MemoryStream(); var enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(mData[m].Emissive)); enc.Save(emissive); } if (mData.Count > 1) { float specularShine = 30f; CurrentSS = 30; if (mData[m].IsBody || mData[m].IsFace) { gm3d.Geometry = mg; gm3d.ModelBody = true; gm3d.Material = new CustomPhongMaterial() { DiffuseColor = PhongMaterials.ToColor(1, 1, 1, 1), SpecularShininess = specularShine, NormalMap = normal, DiffuseMap = diffuse, DiffuseAlphaMap = alpha, SpecularMap = specular, EmissiveMap = emissive }; } else if (!mData[m].IsBody && !second) { gm3d.Geometry = mg; gm3d.Material = new CustomPhongMaterial() { DiffuseColor = PhongMaterials.ToColor(1, 1, 1, 1), SpecularShininess = specularShine, NormalMap = normal, DiffuseMap = diffuse, DiffuseAlphaMap = alpha, SpecularMap = specular, EmissiveMap = emissive }; second = true; } else if (!mData[m].IsBody) { gm3d.Geometry = mg; gm3d.Material = new CustomPhongMaterial() { DiffuseColor = PhongMaterials.ToColor(1, 1, 1, 1), SpecularShininess = specularShine, NormalMap = normal, DiffuseMap = diffuse, DiffuseAlphaMap = alpha, SpecularMap = specular, EmissiveMap = emissive }; } } else { float specularShine = 30f; CurrentSS = 30; gm3d.Geometry = mg; gm3d.Material = new CustomPhongMaterial() { DiffuseColor = PhongMaterials.ToColor(1, 1, 1, 1), SpecularShininess = specularShine, NormalMap = normal, SpecularMap = specular, DiffuseMap = diffuse, DiffuseAlphaMap = alpha, EmissiveMap = emissive }; } return(gm3d); }
private static void SaveScreenshot(Window owner, StatusStrip statusStrip, UIElement source, string filename) { try { RenderTargetBitmap img = ImageProc.GetImage(source, Brushes.White); BitmapFrame frame = BitmapFrame.Create(img); FileStream fStream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write); switch (Path.GetExtension(filename).ToLower()) { case ".jpg": case ".jpeg": case ".jpe": case ".jfif": JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder(); jpgEncoder.QualityLevel = 100; jpgEncoder.Frames.Add(frame); jpgEncoder.Save(fStream); break; case ".png": PngBitmapEncoder pngEncoder = new PngBitmapEncoder(); pngEncoder.Interlace = PngInterlaceOption.On; pngEncoder.Frames.Add(frame); pngEncoder.Save(fStream); break; case ".bmp": BmpBitmapEncoder bmpEncoder = new BmpBitmapEncoder(); bmpEncoder.Frames.Add(frame); bmpEncoder.Save(fStream); break; case ".gif": GifBitmapEncoder gifEncoder = new GifBitmapEncoder(); gifEncoder.Frames.Add(frame); gifEncoder.Save(fStream); break; default: TaskDialog dialog = new TaskDialog(owner, "Error Saving File", "The requested file type is not available.", MessageType.Error); dialog.ShowDialog(); break; } fStream.Close(); statusStrip.UpdateMainStatus("EXPORT SUCCESSFUL"); } catch (Exception exc) { statusStrip.UpdateMainStatus("ERROR: " + exc.Message.ToUpper()); TaskDialog dialog = new TaskDialog(owner, "Error Saving File", exc.Message, MessageType.Error); dialog.ShowDialog(); ExportScreenshot(owner, statusStrip, source, filename, Path.GetDirectoryName(saveDialog.SelectedFile)); } }
public static void ExportImage(GraphicVisual visual, int width, bool addMargin, string filename) { // https://stackoverflow.com/questions/9080231/how-to-save-geometry-as-image var fileExtension = Path.GetExtension(filename).ToLower(); var hasTransparentBackground = fileExtension == ".png"; try { var normalizer = new NormalizeVisual(); var paths = normalizer.Normalize(visual, NormalizeAspect.Width, width); double height = normalizer.AspectRatio * width; var drawingBrush = DrawingBrushBinaryGenerator.Generate(paths); double margin = 0; if (addMargin) { margin = (width > height ? width : height) / 20.0; } double imageWidth = width + 2 * margin; double imageHeight = Math.Ceiling(height + 2 * margin); DrawingVisual viz = new DrawingVisual(); using (DrawingContext dc = viz.RenderOpen()) { if (!hasTransparentBackground) { dc.DrawRectangle(Brushes.White, null, new Rect(0, 0, imageWidth, imageHeight)); } dc.DrawRectangle(drawingBrush, null, new Rect(margin, margin, width, height)); } RenderTargetBitmap bmp = new RenderTargetBitmap((int)imageWidth, (int)imageHeight, // Size 96, 96, // DPI PixelFormats.Pbgra32); bmp.Render(viz); BitmapEncoder encoder = null; switch (fileExtension) { case ".png": encoder = new PngBitmapEncoder(); break; case ".jpg": encoder = new JpegBitmapEncoder(); break; case ".tiff": encoder = new TiffBitmapEncoder(); break; case ".bmp": encoder = new BmpBitmapEncoder(); break; case ".gif": encoder = new GifBitmapEncoder(); break; } encoder.Frames.Add(BitmapFrame.Create(bmp)); using (FileStream file = new FileStream(filename, FileMode.Create)) { encoder.Save(file); } } catch { } }
private async void Encode(List <FrameInfo> listFrames, int id, Parameters param, CancellationTokenSource tokenSource) { var processing = this.DispatcherStringResource("Encoder.Processing"); try { switch (param.Type) { case Export.Gif: #region Gif #region Cut/Paint Unchanged Pixels if (param.EncoderType == GifEncoderType.Legacy || param.EncoderType == GifEncoderType.ScreenToGif) { if (param.DetectUnchangedPixels) { Update(id, 0, FindResource("Encoder.Analyzing").ToString()); if (param.DummyColor.HasValue) { var color = Color.FromArgb(param.DummyColor.Value.R, param.DummyColor.Value.G, param.DummyColor.Value.B); listFrames = ImageMethods.PaintTransparentAndCut(listFrames, color, id, tokenSource); } else { listFrames = ImageMethods.CutUnchanged(listFrames, id, tokenSource); } } else { var size = listFrames[0].Path.ScaledSize(); listFrames.ForEach(x => x.Rect = new Int32Rect(0, 0, (int)size.Width, (int)size.Height)); } } #endregion switch (param.EncoderType) { case GifEncoderType.ScreenToGif: #region Improved encoding using (var stream = new MemoryStream()) { using (var encoder = new GifFile(stream, param.RepeatCount)) { encoder.UseGlobalColorTable = param.UseGlobalColorTable; encoder.TransparentColor = param.DummyColor; encoder.MaximumNumberColor = param.MaximumNumberColors; for (var i = 0; i < listFrames.Count; i++) { if (!listFrames[i].HasArea && param.DetectUnchangedPixels) { continue; } if (listFrames[i].Delay == 0) { listFrames[i].Delay = 10; } encoder.AddFrame(listFrames[i].Path, listFrames[i].Rect, listFrames[i].Delay); Update(id, i, string.Format(processing, i)); #region Cancellation if (tokenSource.Token.IsCancellationRequested) { SetStatus(Status.Canceled, id); break; } #endregion } } try { using (var fileStream = new FileStream(param.Filename, FileMode.Create, FileAccess.Write, FileShare.None, 4096)) stream.WriteTo(fileStream); } catch (Exception ex) { SetStatus(Status.Error, id); LogWriter.Log(ex, "Improved Encoding"); } } #endregion break; case GifEncoderType.Legacy: #region Legacy Encoding using (var encoder = new AnimatedGifEncoder()) { if (param.DummyColor.HasValue) { var color = Color.FromArgb(param.DummyColor.Value.R, param.DummyColor.Value.G, param.DummyColor.Value.B); encoder.SetTransparent(color); encoder.SetDispose(1); //Undraw Method, "Leave". } encoder.Start(param.Filename); encoder.SetQuality(param.Quality); encoder.SetRepeat(param.RepeatCount); var numImage = 0; foreach (var frame in listFrames) { #region Cancellation if (tokenSource.Token.IsCancellationRequested) { SetStatus(Status.Canceled, id); break; } #endregion if (!frame.HasArea && param.DetectUnchangedPixels) { continue; } var bitmapAux = new Bitmap(frame.Path); encoder.SetDelay(frame.Delay); encoder.AddFrame(bitmapAux, frame.Rect.X, frame.Rect.Y); bitmapAux.Dispose(); Update(id, numImage, string.Format(processing, numImage)); numImage++; } } #endregion break; case GifEncoderType.PaintNet: #region paint.NET encoding using (var stream = new MemoryStream()) { using (var encoder = new GifEncoder(stream, null, null, param.RepeatCount)) { for (var i = 0; i < listFrames.Count; i++) { var bitmapAux = new Bitmap(listFrames[i].Path); encoder.AddFrame(bitmapAux, 0, 0, TimeSpan.FromMilliseconds(listFrames[i].Delay)); bitmapAux.Dispose(); Update(id, i, string.Format(processing, i)); #region Cancellation if (tokenSource.Token.IsCancellationRequested) { SetStatus(Status.Canceled, id); break; } #endregion } } stream.Position = 0; try { using (var fileStream = new FileStream(param.Filename, FileMode.Create, FileAccess.Write, FileShare.None, Constants.BufferSize, false)) stream.WriteTo(fileStream); } catch (Exception ex) { SetStatus(Status.Error, id); LogWriter.Log(ex, "Encoding with paint.Net."); } } #endregion break; case GifEncoderType.FFmpeg: #region FFmpeg encoding SetStatus(Status.Processing, id, null, true); if (!Util.Other.IsFfmpegPresent()) { throw new ApplicationException("FFmpeg not present."); } if (File.Exists(param.Filename)) { File.Delete(param.Filename); } #region Generate concat var concat = new StringBuilder(); foreach (var frame in listFrames) { concat.AppendLine("file '" + frame.Path + "'"); concat.AppendLine("duration " + (frame.Delay / 1000d).ToString(CultureInfo.InvariantCulture)); } var concatPath = Path.GetDirectoryName(listFrames[0].Path) ?? Path.GetTempPath(); var concatFile = Path.Combine(concatPath, "concat.txt"); if (!Directory.Exists(concatPath)) { Directory.CreateDirectory(concatPath); } if (File.Exists(concatFile)) { File.Delete(concatFile); } File.WriteAllText(concatFile, concat.ToString()); #endregion param.Command = string.Format(param.Command, concatFile, param.ExtraParameters.Replace("{H}", param.Height.ToString()).Replace("{W}", param.Width.ToString()), param.Filename); var process = new ProcessStartInfo(UserSettings.All.FfmpegLocation) { Arguments = param.Command, CreateNoWindow = true, ErrorDialog = false, UseShellExecute = false, RedirectStandardError = true }; var pro = Process.Start(process); var str = pro.StandardError.ReadToEnd(); var fileInfo = new FileInfo(param.Filename); if (!fileInfo.Exists || fileInfo.Length == 0) { throw new Exception("Error while encoding the gif with FFmpeg.") { HelpLink = $"Command:\n\r{param.Command}\n\rResult:\n\r{str}" } } ; #endregion break; case GifEncoderType.Gifski: #region Gifski encoding SetStatus(Status.Processing, id, null, true); if (!Util.Other.IsGifskiPresent()) { throw new ApplicationException("Gifski not present."); } if (File.Exists(param.Filename)) { File.Delete(param.Filename); } var gifski = new GifskiInterop(); var handle = gifski.Start(UserSettings.All.GifskiQuality, UserSettings.All.Looped); ThreadPool.QueueUserWorkItem(delegate { Thread.Sleep(500); SetStatus(Status.Processing, id, null, false); for (var i = 0; i < listFrames.Count; i++) { Update(id, i, string.Format(processing, i)); gifski.AddFrame(handle, (uint)i, listFrames[i].Path, listFrames[i].Delay); } gifski.EndAdding(handle); }, null); gifski.End(handle, param.Filename); var fileInfo2 = new FileInfo(param.Filename); if (!fileInfo2.Exists || fileInfo2.Length == 0) { throw new Exception("Error while encoding the gif with Gifski.", new Win32Exception()) { HelpLink = $"Command:\n\r{param.Command}\n\rResult:\n\r{Marshal.GetLastWin32Error()}" } } ; #endregion break; default: throw new Exception("Undefined Gif encoder type"); } #endregion break; case Export.Apng: #region Apng #region Cut/Paint Unchanged Pixels if (param.DetectUnchangedPixels) { Update(id, 0, FindResource("Encoder.Analyzing").ToString()); if (param.DummyColor.HasValue) { var color = Color.FromArgb(param.DummyColor.Value.A, param.DummyColor.Value.R, param.DummyColor.Value.G, param.DummyColor.Value.B); listFrames = ImageMethods.PaintTransparentAndCut(listFrames, color, id, tokenSource); } else { listFrames = ImageMethods.CutUnchanged(listFrames, id, tokenSource); } } else { var size = listFrames[0].Path.ScaledSize(); listFrames.ForEach(x => x.Rect = new Int32Rect(0, 0, (int)size.Width, (int)size.Height)); } #endregion #region Encoding using (var stream = new MemoryStream()) { var frameCount = listFrames.Count(x => x.HasArea); using (var encoder = new Apng(stream, frameCount, param.RepeatCount)) { for (var i = 0; i < listFrames.Count; i++) { if (!listFrames[i].HasArea && param.DetectUnchangedPixels) { continue; } if (listFrames[i].Delay == 0) { listFrames[i].Delay = 10; } encoder.AddFrame(listFrames[i].Path, listFrames[i].Rect, listFrames[i].Delay); Update(id, i, string.Format(processing, i)); #region Cancellation if (tokenSource.Token.IsCancellationRequested) { SetStatus(Status.Canceled, id); break; } #endregion } } try { using (var fileStream = new FileStream(param.Filename, FileMode.Create, FileAccess.Write, FileShare.None, 4096)) stream.WriteTo(fileStream); } catch (Exception ex) { SetStatus(Status.Error, id); LogWriter.Log(ex, "Apng Encoding"); } } #endregion #endregion break; case Export.Video: #region Video switch (param.VideoEncoder) { case VideoEncoderType.AviStandalone: #region Avi Standalone var image = listFrames[0].Path.SourceFrom(); if (File.Exists(param.Filename)) { File.Delete(param.Filename); } //1000 / listFrames[0].Delay using (var aviWriter = new AviWriter(param.Filename, param.Framerate, image.PixelWidth, image.PixelHeight, param.VideoQuality)) { var numImage = 0; foreach (var frame in listFrames) { using (var outStream = new MemoryStream()) { var bitImage = frame.Path.SourceFrom(); var enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(bitImage)); enc.Save(outStream); outStream.Flush(); using (var bitmap = new Bitmap(outStream)) aviWriter.AddFrame(bitmap, param.FlipVideo); } Update(id, numImage, string.Format(processing, numImage)); numImage++; #region Cancellation if (tokenSource.Token.IsCancellationRequested) { SetStatus(Status.Canceled, id); break; } #endregion } } #endregion break; case VideoEncoderType.Ffmpg: #region Video using FFmpeg SetStatus(Status.Processing, id, null, true); if (!Util.Other.IsFfmpegPresent()) { throw new ApplicationException("FFmpeg not present."); } if (File.Exists(param.Filename)) { File.Delete(param.Filename); } #region Generate concat var concat = new StringBuilder(); foreach (var frame in listFrames) { concat.AppendLine("file '" + frame.Path + "'"); concat.AppendLine("duration " + (frame.Delay / 1000d).ToString(CultureInfo.InvariantCulture)); } var concatPath = Path.GetDirectoryName(listFrames[0].Path) ?? Path.GetTempPath(); var concatFile = Path.Combine(concatPath, "concat.txt"); if (!Directory.Exists(concatPath)) { Directory.CreateDirectory(concatPath); } if (File.Exists(concatFile)) { File.Delete(concatFile); } File.WriteAllText(concatFile, concat.ToString()); #endregion param.Command = string.Format(param.Command, concatFile, param.ExtraParameters.Replace("{H}", param.Height.ToString()).Replace("{W}", param.Width.ToString()), param.Filename); var process = new ProcessStartInfo(UserSettings.All.FfmpegLocation) { Arguments = param.Command, CreateNoWindow = true, ErrorDialog = false, UseShellExecute = false, RedirectStandardError = true }; var pro = Process.Start(process); var str = pro.StandardError.ReadToEnd(); var fileInfo = new FileInfo(param.Filename); if (!fileInfo.Exists || fileInfo.Length == 0) { throw new Exception("Error while encoding with FFmpeg.") { HelpLink = str } } ; #endregion break; default: throw new Exception("Undefined video encoder"); } #endregion break; default: throw new ArgumentOutOfRangeException(nameof(param)); } //If it was canceled, try deleting the file. if (tokenSource.Token.IsCancellationRequested) { if (File.Exists(param.Filename)) { File.Delete(param.Filename); } SetStatus(Status.Canceled, id); return; } #region Upload if (param.Upload && File.Exists(param.Filename)) { InternalUpdate(id, "Encoder.Uploading", true, true); try { ICloud cloud = CloudFactory.CreateCloud(param.UploadDestinationIndex); var uploadedFile = await cloud.UploadFileAsync(param.Filename, CancellationToken.None); InternalSetUpload(id, true, uploadedFile.Link, uploadedFile.DeleteLink); } catch (Exception e) { LogWriter.Log(e, "It was not possible to run the post encoding command."); InternalSetUpload(id, false, null, null, e); } } #endregion #region Copy to clipboard if (param.CopyToClipboard && File.Exists(param.Filename)) { Dispatcher.Invoke(() => { try { var data = new DataObject(); switch (param.CopyType) { case CopyType.File: if (param.Type != Export.Video) { data.SetImage(param.Filename.SourceFrom()); } data.SetText(param.Filename, TextDataFormat.Text); data.SetFileDropList(new StringCollection { param.Filename }); break; case CopyType.FolderPath: data.SetText(Path.GetDirectoryName(param.Filename) ?? param.Filename, TextDataFormat.Text); break; case CopyType.Link: var link = InternalGetUpload(id); data.SetText(string.IsNullOrEmpty(link) ? param.Filename : link, TextDataFormat.Text); break; default: data.SetText(param.Filename, TextDataFormat.Text); break; } //It tries to set the data to the clipboard 10 times before failing it to do so. //This issue may happen if the clipboard is opened by any clipboard manager. for (var i = 0; i < 10; i++) { try { Clipboard.SetDataObject(data, true); break; } catch (COMException ex) { if ((uint)ex.ErrorCode != 0x800401D0) //CLIPBRD_E_CANT_OPEN { throw; } } Thread.Sleep(100); } InternalSetCopy(id, true); } catch (Exception e) { LogWriter.Log(e, "It was not possible to copy the file."); InternalSetCopy(id, false, e); } }); } #endregion #region Execute commands if (param.ExecuteCommands && !string.IsNullOrWhiteSpace(param.PostCommands)) { InternalUpdate(id, "Encoder.Executing", true, true); var command = param.PostCommands.Replace("{p}", "\"" + param.Filename + "\"").Replace("{f}", "\"" + Path.GetDirectoryName(param.Filename) + "\""); var output = ""; try { foreach (var com in command.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)) { var procStartInfo = new ProcessStartInfo("cmd", "/c " + com) { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; using (var process = new Process()) { process.StartInfo = procStartInfo; process.Start(); var message = process.StandardOutput.ReadToEnd(); var error = process.StandardError.ReadToEnd(); if (!string.IsNullOrWhiteSpace(message)) { output += message + Environment.NewLine; } if (!string.IsNullOrWhiteSpace(message)) { output += message + Environment.NewLine; } if (!string.IsNullOrWhiteSpace(error)) { throw new Exception(error); } process.WaitForExit(1000); } } InternalSetCommand(id, true, command, output); } catch (Exception e) { LogWriter.Log(e, "It was not possible to run the post encoding command."); InternalSetCommand(id, false, command, output, e); } } #endregion if (!tokenSource.Token.IsCancellationRequested) { SetStatus(Status.Completed, id, param.Filename); } } catch (Exception ex) { LogWriter.Log(ex, "Encode"); SetStatus(Status.Error, id, null, false, ex); } finally { #region Delete Encoder Folder try { var encoderFolder = Path.GetDirectoryName(listFrames[0].Path); if (!string.IsNullOrEmpty(encoderFolder)) { if (Directory.Exists(encoderFolder)) { Directory.Delete(encoderFolder, true); } } } catch (Exception ex) { LogWriter.Log(ex, "Cleaning the Encode folder"); } #endregion GC.Collect(); } }