Exemplo n.º 1
0
 private void bGenerate_Click(object sender, EventArgs e)
 {
     if (bmp1 != null && bmp2 != null)
     {
         if (bmp1.Width == bmp2.Width && bmp1.Height == bmp2.Height)
         {
             if (bmp1.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb && bmp2.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb)
             {
                 tProgress.Text = "Gathering frames...";
                 GifBitmapEncoder generatedWyMerge = GenerateWyMerge(bmp1, bmp2, tbFrames.Value, tbThreshold.Value);
                 SaveFileDialog   sfd = new SaveFileDialog();
                 sfd.Filter = "GIF Image (*.gif)|*.gif";
                 sfd.Title  = "Save " + generatedWyMerge.Frames.Count + " frame WyMerge";
                 if (sfd.ShowDialog() == DialogResult.OK)
                 {
                     FileStream stream = (FileStream)sfd.OpenFile();
                     generatedWyMerge.Save(stream);
                     stream.Close();
                 }
             }
             else
             {
                 MessageBox.Show("WyMerge currently only supports 24-bit RGB bitmaps.\n\nBitmap 1: " + bmp1.PixelFormat.ToString() + "\nBitmap 2: " + bmp2.PixelFormat.ToString(), "Whoops...");
             }
         }
         else
         {
             MessageBox.Show("Both bitmaps need to be the same dimensions, else the WyMerge can\'t generate!\n\nBitmap 1: " + bmp1.Width + " x " + bmp1.Height + "\nBitmap 2: " + bmp2.Width + " x " + bmp2.Height, "Whoops...");
         }
     }
     else
     {
         MessageBox.Show("Both bitmaps need to be loaded before generating a WyMerge!", "Whoops...");
     }
 }
Exemplo n.º 2
0
        public static void CreateAnimation(ScreenCapture sc, int frames, int wait, string filename)
        {
            var encoder = new GifBitmapEncoder();

            for (var i = 0; i < frames; i++)
            {
                using (var bmp = sc.GetBitmapOfScreen())
                {
                    var size   = BitmapSizeOptions.FromEmptyOptions();
                    var source = Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, size);
                    var frame  = BitmapFrame.Create(source);
                    encoder.Frames.Add(frame);
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                Thread.Sleep(wait);
            }

            Thread.Sleep(1000);
            using (var fs = new FileStream(filename, FileMode.Create))
            {
                encoder.Save(fs);
                encoder.Frames.Clear();
                encoder = null;
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
Exemplo n.º 3
0
        /// <summary>
        /// Writes each layer out to an animated GIF file
        /// </summary>
        /// <param name="strFilePath">Output file name</param>
        /// <returns>True if successful, False if error</returns>
        public Boolean WriteToGif(String strFilePath)
        {
            List <Bitmap> images      = new List <Bitmap>();
            int           nLayerCount = GetLayerCount();

            for (int nLayer = 0; nLayer < nLayerCount; nLayer++)
            {
                Bitmap bitmap = new Bitmap(Convert.ToInt32(m_dWidth), Convert.ToInt32(m_dHeight), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                images.Add(bitmap);
                Graphics   g     = Graphics.FromImage(bitmap);
                Rectangle  rRect = new Rectangle(0, 0, (int)m_dWidth, (int)m_dHeight);
                SolidBrush brush = new SolidBrush(Color.White);
                g.FillRectangle(brush, rRect);
                SelectLayer(nLayer);
                Draw(1, g, 0, 0);
                brush.Dispose();
            }
            System.Windows.Media.Imaging.GifBitmapEncoder gEnc = new GifBitmapEncoder();
            foreach (System.Drawing.Bitmap bmpImage in images)
            {
                var bmp = bmpImage.GetHbitmap();
                var src = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    bmp,
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());
                gEnc.Frames.Add(BitmapFrame.Create(src));
            }
            using (FileStream fs = new FileStream(strFilePath, FileMode.Create))
            {
                gEnc.Save(fs);
            }
            return(true);
        }
Exemplo n.º 4
0
        private void SaveAsGif_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog _sfd = new SaveFileDialog();

            _sfd.Title  = "Save Game As GIF.";
            _sfd.Filter = "GIF Files (*.gif) | *.gif";

            if (_sfd.ShowDialog() == true)
            {
                using (FileStream _fs = new FileStream(_sfd.FileName, FileMode.Create, FileAccess.Write))
                {
                    try
                    {
                        _encoder.Save(_fs);
                    }
                    catch (Exception _exc)
                    {
                        this.ViewModel.ErrorString = _exc.Message;
                    }
                    _fs.Flush();
                    _fs.Close();
                }
            }

            _encoder = new GifBitmapEncoder();
        }
Exemplo n.º 5
0
        private void RecordGif(int frames, int interval)
        {
            _gifBitmapEncoder = new GifBitmapEncoder();

            for (var i = 0; i < frames; i++)
            {
                _capture.CaptureScreen();
                Thread.Sleep(interval);
            }

            _path = new RelativeFile
            {
                SubDirectory         = "Animations",
                Name                 = "GifRecording",
                Extension            = ".gif",
                TimeStampFile        = true,
                UseDetailedTimeStamp = true
            };

            using (var filestream = new FileStream(_path.GetFullPath(), FileMode.Create))
            {
                _gifBitmapEncoder.Save(filestream);
            }

            _gifBitmapEncoder = null;
        }
Exemplo n.º 6
0
        /// <summary>
        /// Ulozi obrazek ve formatu GIF
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="delay"></param>
        /// <param name="repeat"></param>
        public void SaveToGif(string path, short delay, bool repeat)
        {
            AnimatedGifEncoder aniEncoder = new AnimatedGifEncoder();

            aniEncoder.Start(path);
            aniEncoder.SetDelay(delay);
            aniEncoder.SetRepeat(repeat ? 0 : -1);

            using (MemoryStream memoryStream = new MemoryStream())
            {
                int lastIndex = morphManager.KeyFrames[morphManager.KeyFrames.Count - 1].Index;
                for (int i = 0; i <= lastIndex; i++)
                {
                    Morphing.Core.Frame frame = morphManager.GetFrame(i);
                    if (frame.WarpedBitmap == null)
                    {
                        continue;
                    }

                    // Vytvoreni gif obrazku a vlozeni do kolekce snimku
                    GifBitmapEncoder gifEncoder = new GifBitmapEncoder();
                    gifEncoder.Frames.Add(BitmapFrame.Create(frame.WarpedBitmap));
                    gifEncoder.Save(memoryStream);
                    aniEncoder.AddFrame(System.Drawing.Image.FromStream(memoryStream));
                    memoryStream.Seek(0, SeekOrigin.Begin);
                }
                aniEncoder.Finish();
            }
            selectedFrame.ApplyWarping();
        }
Exemplo n.º 7
0
        /// <summary>
        /// 儲存 BitmapIimage 影像
        /// </summary>
        /// <param name="bitmapSource">BitmapSource資料來源</param>
        /// <param name="fileName">儲存路徑</param>
        /// <param name="encoder">編碼</param>
        public static void SaveUsingEncoder(BitmapSource bitmapSource, string fileName, string extension)
        {
            using (var stream = File.Create(fileName))
            {
                BitmapEncoder encoder;
                switch (extension.ToUpper())
                {
                case ".JPG":
                case ".JPEG":
                    encoder = new JpegBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
                    encoder.Save(stream);
                    break;

                case ".PNG":
                    encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
                    encoder.Save(stream);
                    break;

                case ".GIF":
                    encoder = new GifBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
                    encoder.Save(stream);
                    break;
                }
            }
        }
Exemplo n.º 8
0
        private void ZapiszGIF(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.FileName = "ImageGIF";
            saveFileDialog.Filter   = "GIF (*.gif)|*.gif";
            if (saveFileDialog.ShowDialog() == true)
            {
                try
                {
                    var         encoder = new GifBitmapEncoder();
                    BitmapImage obr     = new BitmapImage();

                    encoder.Frames.Add(BitmapFrame.Create((BitmapSource)obrazek.Source));
                    using (var stream = saveFileDialog.OpenFile())
                    {
                        encoder.Save(stream);
                    }
                }
                catch (Exception eeee)
                {
                    MessageBox.Show(eeee.Message);
                    MessageBox.Show("Błąd przy zapisie!", "Zapis do pliku", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        }
Exemplo n.º 9
0
        private void OnExportMovie()
        {
            var saveDialog = new SaveFileDialog()
            {
                Filter          = "Gif Files|*.gif",
                AddExtension    = true,
                OverwritePrompt = true,
                ValidateNames   = true
            };

            if (saveDialog.ShowDialog() == true)
            {
                var frames = new List <WriteableBitmap>(this.Frames);
                var path   = saveDialog.FileName;

                ThreadPool.QueueUserWorkItem(_ =>
                {
                    var encoder = new GifBitmapEncoder();

                    foreach (var frame in frames)
                    {
                        var bitmapFrame = BitmapFrame.Create(frame);
                        encoder.Frames.Add(bitmapFrame);
                    }

                    using (var file = File.OpenWrite(path))
                    {
                        encoder.Save(file);
                    }
                });
            }
        }
Exemplo n.º 10
0
        private static void GifCoderTest()
        {
            var _gifFileName = "F_LAW.gif";

            var _input = new FileStream(_gifFileName, FileMode.Open);

            var _gifCoder = new GifBitmapCoder();

            _gifCoder.Load(_input);
            _input.Close();

            for (int i = 0; i < _gifCoder.Frames.Count; i++)
            {
                var _output  = String.Format(@"result\{0}{1:d3}.gif", Path.GetFileNameWithoutExtension(_gifFileName), i);
                var _encoder = new GifBitmapEncoder();
                _encoder.Frames.Add(_gifCoder.Frames[i].Frame);

                using (var _fs = new FileStream(_output, FileMode.Create))
                {
                    _encoder.Save(_fs);
                }
            }

            var _output1 = new FileStream("output.gif", FileMode.Create);

            _gifCoder.Save(_output1);
            _output1.Close();
        }
Exemplo n.º 11
0
        /// <summary>
        /// 将图片保存到文件
        /// </summary>
        /// <param name="bitmap">BitmapSource</param>
        /// <param name="format">图像类型</param>
        /// <param name="fileName">保存文件名</param>
        public static void ImageToFile(BitmapSource bitmap, ImageFormat format, string fileName)
        {
            BitmapEncoder encoder;

            switch (format)
            {
            case ImageFormat.JPG:
                encoder = new JpegBitmapEncoder();
                break;

            case ImageFormat.PNG:
                encoder = new PngBitmapEncoder();
                break;

            case ImageFormat.BMP:
                encoder = new BmpBitmapEncoder();
                break;

            case ImageFormat.GIF:
                encoder = new GifBitmapEncoder();
                break;

            default:
                throw new InvalidOperationException();
            }

            FileStream fs = new FileStream(fileName, FileMode.Create);

            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.Save(fs);
            fs.Dispose();
            fs.Close();
        }
Exemplo n.º 12
0
        public static void CaptureOutGifAnimation(
            string path,
            MediaPlayer player,
            double startSeconds             = 0,
            double waitSeconds              = 0.1,
            int count                       = 10,
            double maxWidth                 = 640,
            CRGBA3x3FilteringProc filtering = null,
            int dpi = Image.DEFAULT_dpi)
        {
            if (player is null)
            {
                return;
            }

            // 読み込みが完了するまで待機
            waitMediaSetup(player);

            int width, height;

            // リサイズ後のサイズを計算
            calcRectSize(player, maxWidth, out width, out height);

            double volume = player.Volume;

            player.Volume = 0;

            var gEnc = new GifBitmapEncoder();

            for (int i = 0; i < count; ++i)
            {
                // 指定位置へシーク
                double pos = startSeconds + (double)i * waitSeconds;
                player.Position = TimeSpan.FromSeconds(pos);
                player.Pause();

                // 読み込みが完了するまで待機
                waitMediaSetup(player, pos);

                var renderTarget = new RenderTargetBitmap(width, height, dpi, dpi, PixelFormats.Pbgra32);

                capture(
                    renderTarget,
                    player,
                    width,
                    height,
                    filtering,
                    dpi
                    );

                gEnc.Frames.Add(BitmapFrame.Create(renderTarget));
            }

            player.Volume = volume;

            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                gEnc.Save(fs);
            }
        }
Exemplo n.º 13
0
        public static string saveAs_Gif(this Image image, string pathToSaveImage)
        {
            return((string)image.wpfInvoke(
                       () =>
            {
                try
                {
                    using (FileStream outStream = new FileStream(pathToSaveImage, FileMode.Create))
                    {
                        var gifBitmapEncoder = new GifBitmapEncoder();
                        gifBitmapEncoder.Frames.Add(BitmapFrame.Create((BitmapImage)image.Source));        //BitmapFrame.Create(image));

                        gifBitmapEncoder.Save(outStream);
                    }
                }
                catch (Exception ex)
                {
                    ex.log("in WPF Image saveas_Gif");
                }
                if (pathToSaveImage.fileExists())
                {
                    return pathToSaveImage;
                }
                return "";
            }));
        }
Exemplo n.º 14
0
 /// <summary>
 /// Saves a Gif image to the file system
 /// </summary>
 /// <param name="filename"></param>
 /// <param name="gifEnconder"></param>
 internal static void SaveGif(string filename, GifBitmapEncoder gifEnconder)
 {
     using (FileStream stream = new FileStream(filename, FileMode.Create))
     {
         gifEnconder.Save(stream);
     }
 }
Exemplo n.º 15
0
        private void SaveWriteableBitmap(WriteableBitmap bitmap, string filename, FileFormat format)
        {
            using (FileStream stream = new FileStream(filename, FileMode.Create))
            {
                switch (format)
                {
                case FileFormat.Jpeg:
                    JpegBitmapEncoder encoder1 = new JpegBitmapEncoder();
                    encoder1.Frames.Add(BitmapFrame.Create(bitmap));
                    encoder1.Save(stream);
                    break;

                case FileFormat.Bmp:
                    BmpBitmapEncoder encoder2 = new BmpBitmapEncoder();
                    encoder2.Frames.Add(BitmapFrame.Create(bitmap));
                    encoder2.Save(stream);
                    break;

                case FileFormat.Png:
                    PngBitmapEncoder encoder3 = new PngBitmapEncoder();
                    encoder3.Frames.Add(BitmapFrame.Create(bitmap));
                    encoder3.Save(stream);
                    break;

                case FileFormat.Gif:
                    GifBitmapEncoder encoder4 = new GifBitmapEncoder();
                    encoder4.Frames.Add(BitmapFrame.Create(bitmap));
                    encoder4.Save(stream);
                    break;
                }
            }
        }
Exemplo n.º 16
0
        private void ButtonSave_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Filter = "Images|*.png;*.bmp;*.jpg";
            ImageFormat format = ImageFormat.Png;

            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string ext = System.IO.Path.GetExtension(sfd.FileName);
                switch (ext)
                {
                case ".jpg":
                    format = ImageFormat.Jpeg;
                    break;

                case ".bmp":
                    format = ImageFormat.Bmp;
                    break;
                }
                this.inkCanvas1.EditingMode = InkCanvasEditingMode.None;
                string             imgPath = sfd.FileName;
                MemoryStream       ms      = new MemoryStream();
                FileStream         fs      = new FileStream(imgPath, FileMode.Create);
                RenderTargetBitmap rtb     = new RenderTargetBitmap((int)inkCanvas1.Width, (int)inkCanvas1.Height, 96, 96, PixelFormats.Default);
                rtb.Render(inkCanvas1);
                GifBitmapEncoder gifEnc = new GifBitmapEncoder();
                gifEnc.Frames.Add(BitmapFrame.Create(rtb));
                gifEnc.Save(fs);
                fs.Close();
                this.inkCanvas1.EditingMode = InkCanvasEditingMode.Ink;
                MessageBox.Show("File has saved, " + imgPath);
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Write the bitmap to the file in the encoding implied by the extension of the
        /// destination file.
        /// </summary>
        /// <param name="Bitmap"></param>
        /// <param name="ToFilePath"></param>
        public static void WriteToFile(this BitmapSource Bitmap, string ToFilePath)
        {
            var ext = global::System.IO.Path.GetExtension(ToFilePath).ToLower();
            var ms  = new MemoryStream();

            if ((ext == ".jpg") || (ext == ".jpeg"))
            {
                var encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(Bitmap));
                encoder.Save(ms);
            }

            else if ((ext == ".tif") || (ext == ".tiff"))
            {
                var encoder = new TiffBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(Bitmap));
                encoder.Save(ms);
            }

            else if (ext == ".png")
            {
                var encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(Bitmap));
                encoder.Save(ms);
            }

            else if (ext == ".bmp")
            {
                var encoder = new BmpBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(Bitmap));
                encoder.Save(ms);
            }

            else if (ext == ".gif")
            {
                var encoder = new GifBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(Bitmap));
                encoder.Save(ms);
            }

            else if (ext == ".wmp")
            {
                var encoder = new WmpBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(Bitmap));
                encoder.Save(ms);
            }

            else
            {
                throw new Exception("extension of file " + ToFilePath + " not supported.");
            }

            byte[] bytes = new byte[ms.Length];
            ms.Seek(0, SeekOrigin.Begin);
            ms.Read(bytes, 0, (int)ms.Length);
            ms.Close();

            global::System.IO.File.WriteAllBytes(ToFilePath, bytes);
        }
Exemplo n.º 18
0
        public void Save(Stream aStream)
        {
            this.BehaviorExtention.Save(aStream);

            foreach (var _extention in this.Extensions)
            {
                _extention.Save(aStream);
            }

            aStream.WriteByte(Separator);

            var _bw = new BinaryWriter(aStream);

            _bw.Write(this.FOffsetX);
            _bw.Write(this.FOffsetY);
            _bw.Write((UInt16)this.Width);
            _bw.Write((UInt16)this.Height);
            _bw.Write(this.ImageFlags);

            if (!this.UseGlobalPalette)
            {
                foreach (var _c in this.FFrame.Palette.Colors)
                {
                    _bw.Write(_c.R);
                    _bw.Write(_c.G);
                    _bw.Write(_c.B);
                }
            }

            var _gifEncoder = new GifBitmapEncoder();

            _gifEncoder.Frames.Add(this.FFrame);

            var _buff = new MemoryStream();

            _gifEncoder.Save(_buff);

            // find image data start position
            var _fileHeaderSize = 13;

            _buff.Seek(_fileHeaderSize, SeekOrigin.Begin);

            GifExtension _ext = null;

            while ((_ext = GifExtension.Load(_buff)) != null)
            {
                ;
            }
            var _imageDataStart = (int)_buff.Position;

            var _data = _buff.ToArray();

            _buff.Close();

            var _imageHeaderSize        = 9;
            int _imageDataStartPosition = _imageDataStart + _imageHeaderSize + this.FFrame.Palette.Colors.Count * 3;

            _bw.Write(_data, _imageDataStartPosition, _data.Length - _imageDataStartPosition - 1);
        }
Exemplo n.º 19
0
        //画像を保存
        private void ButtonSave_Click(object sender, RoutedEventArgs e)
        {
            if (MyOriginBitmap == null)
            {
                return;
            }
            var saveFileDialog = new Microsoft.Win32.SaveFileDialog();

            //saveFileDialog.Filter = "*.png|*.png|*.jpg|*.jpg;*.jpeg|*.bmp|*.bmp|*.gif|*.gif|*.tiff|*.tiff|*.wdp|*.wdp;*jxr";
            saveFileDialog.Filter       = "*.png|*.png|*.jpg|*.jpg;*.jpeg|*.bmp|*.bmp|*.gif|*.gif";
            saveFileDialog.AddExtension = true;//ファイル名に拡張子追加

            //初期フォルダ指定、開いている画像と同じフォルダ
            saveFileDialog.InitialDirectory = System.IO.Path.GetDirectoryName(ImageFileFullPath);
            saveFileDialog.FileName         = System.IO.Path.GetFileNameWithoutExtension(ImageFileFullPath) + "_";
            if (saveFileDialog.ShowDialog() == true)
            {
                BitmapEncoder encoder = null;
                switch (saveFileDialog.FilterIndex)
                {
                case 1:
                    encoder = new PngBitmapEncoder();
                    break;

                case 2:
                    encoder = new JpegBitmapEncoder();
                    break;

                case 3:
                    encoder = new BmpBitmapEncoder();
                    break;

                case 4:
                    encoder = new GifBitmapEncoder();
                    break;

                //case 5:
                //    //tiffは圧縮方式をコンボボックスから取得
                //    var tiff = new TiffBitmapEncoder();
                //    tiff.Compression = (TiffCompressOption)ComboboxTiffCompress.SelectedItem;
                //    encoder = tiff;
                //    break;
                //case 6:
                //    //wmpはロスレス指定、じゃないと1bppで保存時に画像が崩れるしファイルサイズも大きくなる
                //    var wmp = new WmpBitmapEncoder();
                //    wmp.ImageQualityLevel = 1.0f;
                //    encoder = wmp;
                //    break;
                default:
                    break;
                }

                encoder.Frames.Add(BitmapFrame.Create((BitmapSource)MyImage.Source));
                using (var fs = new FileStream(saveFileDialog.FileName, FileMode.Create, FileAccess.Write))
                {
                    encoder.Save(fs);
                }
            }
        }
Exemplo n.º 20
0
        // Encodes an image to the specified format in memory
        private byte[] memEncode()
        {
            byte[] bytes = null;

            using (MemoryStream stream = new MemoryStream())
            {
                switch (termExt)
                {
                case "bmp":
                    BmpBitmapEncoder bmpEncoder = new BmpBitmapEncoder();
                    bmpEncoder.Frames.Add(BitmapFrame.Create(backupBuffer));
                    bmpEncoder.Save(stream);
                    break;

                case "jpg":
                    JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder();
                    jpgEncoder.Frames.Add(BitmapFrame.Create(backupBuffer));
                    jpgEncoder.Save(stream);
                    break;

                case "gif":
                    GifBitmapEncoder gifEncoder = new GifBitmapEncoder();
                    gifEncoder.Frames.Add(BitmapFrame.Create(backupBuffer));
                    gifEncoder.Save(stream);
                    break;

                case "png":
                    PngBitmapEncoder pngEncoder = new PngBitmapEncoder();
                    // pngEncoder.Interlace = PngInterlaceOption.On;
                    pngEncoder.Frames.Add(BitmapFrame.Create(backupBuffer));
                    pngEncoder.Save(stream);
                    break;

                case "tiff":
                    TiffBitmapEncoder tiffEncoder = new TiffBitmapEncoder();
                    tiffEncoder.Frames.Add(BitmapFrame.Create(backupBuffer));
                    tiffEncoder.Save(stream);
                    break;

                case "jp2":
                    bytes = new byte[height * stride];
                    backupBuffer.CopyPixels(bytes, stride, 0);
                    byte[] header = Encoding.ASCII.GetBytes("P6\n" + width + " " + height + "\n255\n");
                    stream.Write(header, 0, header.Length);
                    foreach (byte curByte in bytes)
                    {
                        stream.WriteByte(curByte);
                    }
                    bytes = J2kImage.ToBytes(J2kImage.CreateEncodableSource(stream));
                    return(bytes);

                default:
                    break;
                }
                bytes = stream.ToArray();
            }
            return(bytes);
        }
        public byte[] getGIFFromImageControl(BitmapImage imageC)
        {
            MemoryStream     memStream = new MemoryStream();
            GifBitmapEncoder encoder   = new GifBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(imageC));
            encoder.Save(memStream);
            return(memStream.GetBuffer());
        }
Exemplo n.º 22
0
 /// <summary>
 /// Сохранить изображение в формате GIF (Graphics Interchange Format).
 /// </summary>
 /// <param name="bmp">Сохраняемое изображение</param>
 /// <param name="path">Путь по которому будет сохранено изображение</param>
 public static void SaveInGif(BitmapSource bmp, string path)
 {
     using (FileStream fileStream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None))
     {
         GifBitmapEncoder gifEncoder = new GifBitmapEncoder();
         gifEncoder.Frames.Add(BitmapFrame.Create(bmp));
         gifEncoder.Save(fileStream);
     }
 }
Exemplo n.º 23
0
        private void SaveAnimation(IEnumerable <Bitmap> images, string path, int?width = null)
        {
            // If a width has been provided, scale the source images down to that width

            IEnumerable <Bitmap> smallImages = null;

            if (width != null && width.HasValue)
            {
                var first = images.First <System.Drawing.Bitmap>();
                var w     = width != null && width.HasValue ? width.Value : first.Width;
                var h     = first.Height * w / first.Width;

                smallImages = from img in images
                              select new Bitmap(img, w, h);
                images = smallImages;
            }

            // From: https://stackoverflow.com/questions/1196322/how-to-create-an-animated-gif-in-net

            var enc = new GifBitmapEncoder();

            foreach (var bmpImage in images)
            {
                var bmp = bmpImage.GetHbitmap();
                var src = Imaging.CreateBitmapSourceFromHBitmap(
                    bmp,
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());
                enc.Frames.Add(BitmapFrame.Create(src));
                DeleteObject(bmp); // recommended, handle memory leak
            }

            // Hack to make the image loop
            // From: https://stackoverflow.com/questions/18719302/net-creating-a-looping-gif-using-gifbitmapencoder

            using (var ms = new MemoryStream())
            {
                enc.Save(ms);
                var fileBytes = ms.ToArray();
                // This is the NETSCAPE2.0 Application Extension.
                var applicationExtension = new byte[] { 33, 255, 11, 78, 69, 84, 83, 67, 65, 80, 69, 50, 46, 48, 3, 1, 0, 0, 0 };
                var newBytes             = new List <byte>();
                newBytes.AddRange(fileBytes.Take(13));
                newBytes.AddRange(applicationExtension);
                newBytes.AddRange(fileBytes.Skip(13));
                File.WriteAllBytes(path, newBytes.ToArray());
            }

            if (smallImages != null)
            {
                foreach (var image in smallImages)
                {
                    image.Dispose();
                }
            }
        }
Exemplo n.º 24
0
        public static void Save(string outpuFilename)
        {
            try
            {
                _Logger.Info("ScreenRecorder.Save()");
                var gifBitmapEncoder = new GifBitmapEncoder();
                var fileStreamList   = new List <FileStream>();

                try
                {
                    _Logger.Info("ScreenRecorder.Save() encode PNG to GIF");
                    foreach (string pngFile in Directory.GetFiles(tempSnapshotDir, "*.png", SearchOption.TopDirectoryOnly)) // efficiency !!! create list like Counter !!!
                    {
                        var tempStream  = new FileStream(pngFile, FileMode.Open);
                        var bitmapFrame = BitmapFrame.Create(tempStream);

                        fileStreamList.Add(tempStream);
                        gifBitmapEncoder.Frames.Add(bitmapFrame);
                        //tempStream.
                    }

                    //GC.Collect();
                    //GC.WaitForPendingFinalizers();

                    GC.Collect(2);

                    _Logger.Info("ScreenRecorder.Save() save GIF");
                    using (var fileStream = new FileStream(outpuFilename, FileMode.Create, FileAccess.Write))
                    {
                        gifBitmapEncoder.Save(fileStream);
                    }
                    _Logger.Info("ScreenRecorder.Save() GIF Seved!");
                }
                catch (Exception e)
                {
                    _Logger.Info("ScreenRecorder.Save() Exception !!!  {0} {1} {2} {3}", e.Message, e.InnerException, e.StackTrace, e.Source);
                    throw;
                }
                finally
                {
                    _Logger.Info("ScreenRecorder.Save() gifBitmapEncoder.Clear()");
                    gifBitmapEncoder.Frames.Clear();

                    _Logger.Info("ScreenRecorder.Save() fileStreamList.Clear()");
                    fileStreamList.ForEach(x => x.Dispose());
                    fileStreamList.Clear();
                }

                _Logger.Info("ScreenRecorder.Save() returning");
            }
            catch (Exception e)
            {
                _Logger.Info("ScreenRecorder.Save() Exception !!! {0} {1} {2} {3}", e.Message, e.InnerException, e.StackTrace, e.Source);
                throw;
            }
        }
        public static bool Save(List <Bitmap> bmps, string path)
        {
            //Check the formats
            if (Formats == null || Formats.Count == 0)
            {
                AddFormats();
            }

            //No images?
            if (bmps.Count == 0)
            {
                return(false);
            }
            bmps.Reverse();
            //to get the right direction


            //Encoder
            GifBitmapEncoder encoder = new GifBitmapEncoder();

            //Add all bmps

            foreach (Bitmap bmp in bmps)
            {
                //Known Format?
                if (!Formats.ContainsKey(bmp.PixelFormat))
                {
                    return(false);
                }

                //Get the bmpdata
                Rectangle rc = new Rectangle(0, 0, bmp.Width, bmp.Height);
                System.Drawing.Imaging.BitmapData bmpData = null;
                bmpData = bmp.LockBits(rc, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);

                byte[] pixels = new byte[rc.Height * bmpData.Stride];

                Marshal.Copy(bmpData.Scan0, pixels, 0, pixels.Length);
                bmp.UnlockBits(bmpData);


                //Add to the gif
                BitmapSource bmpsrc = BitmapSource.Create(rc.Width, rc.Height, 96, 96, Formats[bmp.PixelFormat], null, pixels, bmpData.Stride);
                encoder.Frames.Add(BitmapFrame.Create(bmpsrc));
            }



            //Safe gif
            using (FileStream fstream = new FileStream(path, FileMode.CreateNew))
            {
                encoder.Save(fstream);
            }

            return(true);
        }
Exemplo n.º 26
0
        public H(string a)
        {
            var f = G(a);
            var n = new Func <I>(() =>
            {
                var r = new I();
                L(f.Count, i => { r.Add(R(f[i])); });
                return(r);
            }).Invoke();
            var s = n.Select(d => M((Bitmap)d)).ToList();
            int w = n[0].Width, h = n[0].Height, y = A(K1), q = A(K2), l = A(K3), k = A(K4);

            A(K1, w < y ? y : w);
            A(K2, h < q ? q : h);
            A(K5, w < l ? w : l);
            A(K6, h < k ? h : k);

            GetWindowRect(Process.GetCurrentProcess().MainWindowHandle, ref OP);

            var save = 1;
            var e    = new List <Bitmap>();
            var b    = 0;

            while (f.Count > 1)
            {
                K p = null;
                L(s.Count, i =>
                {
                    var m = s[i];
                    if (i > 0)
                    {
                        p = s[i - 1];
                    }
                    var r = E(m, p, save);
                    if (r != null)
                    {
                        e.Add(r);
                    }
                });
                if (save == 0)
                {
                    continue;
                }
                var g = new GifBitmapEncoder();
                for (var i = 0; i < 3; i++)
                {
                    foreach (var r in e.Select(o => Imaging.CreateBitmapSourceFromHBitmap(o.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions())))
                    {
                        g.Frames.Add(BitmapFrame.Create(r));
                    }
                }
                g.Save(new FileStream("1.gif", FileMode.Create));
                save = 0;
            }
            E(s[0], null, save);
        }
Exemplo n.º 27
0
        public static void ConvertByteToGIF(BitmapSource imageData, string path)
        {
            FileStream       stream  = new FileStream(path, FileMode.Create);
            GifBitmapEncoder encoder = new GifBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(imageData));
            encoder.Save(stream);
            encoder = null;
            stream.Close();
        }
Exemplo n.º 28
0
        public void Dispose()
        {
            var outputPath = @"C:\Source\EpidemicSimulator\EpidemicSimulator\Output\output.gif";

            File.Delete(outputPath);
            using (FileStream fs = new FileStream(outputPath, FileMode.Create))
            {
                _encoder.Save(fs);
            }
        }
Exemplo n.º 29
0
        //        「名前を付けて保存」ダイアログボックスを表示する - .NET Tips(VB.NET, C#...)
        //https://dobon.net/vb/dotnet/form/savefiledialog.html
        //画像保存
        private void SaveImage()
        {
            var saveFileDialog = new Microsoft.Win32.SaveFileDialog();

            saveFileDialog.Filter       = "*.png|*.png|*.jpg|*.jpg;*.jpeg|*.bmp|*.bmp|*.gif|*.gif|*.tiff|*.tiff|*.wdp|*.wdp;*jxr";
            saveFileDialog.AddExtension = true;//ファイル名に拡張子追加
            //初期フォルダ指定、開いている画像と同じフォルダ
            saveFileDialog.InitialDirectory = System.IO.Path.GetDirectoryName(ImageFileFullPath);
            saveFileDialog.FileName         = GetSaveFileName();
            if (saveFileDialog.ShowDialog() == true)
            {
                BitmapEncoder encoder = null;
                switch (saveFileDialog.FilterIndex)
                {
                case 1:
                    encoder = new PngBitmapEncoder();
                    break;

                case 2:
                    encoder = new JpegBitmapEncoder();
                    break;

                case 3:
                    encoder = new BmpBitmapEncoder();
                    break;

                case 4:
                    encoder = new GifBitmapEncoder();
                    break;

                case 5:
                    //tiffは圧縮方式をコンボボックスから取得
                    var tiff = new TiffBitmapEncoder();
                    tiff.Compression = (TiffCompressOption)ComboboxTiffCompress.SelectedItem;
                    encoder          = tiff;
                    break;

                case 6:
                    //wmpはロスレス指定、じゃないと1bppで保存時に画像が崩れるしファイルサイズも大きくなる
                    var wmp = new WmpBitmapEncoder();
                    wmp.ImageQualityLevel = 1.0f;
                    encoder = wmp;
                    break;

                default:
                    break;
                }

                encoder.Frames.Add(BitmapFrame.Create(GetSaveImage()));
                using (var fs = new FileStream(saveFileDialog.FileName, FileMode.Create, FileAccess.Write))
                {
                    encoder.Save(fs);
                }
            }
        }
Exemplo n.º 30
0
        private void SaveFile(string fileName)
        {
            RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
                (int)canvas.Width, (int)canvas.Height,
                96d, 96d, System.Windows.Media.PixelFormats.Default);

            canvas.Measure(new Size((int)canvas.Width, (int)canvas.Height));
            canvas.Arrange(new Rect(new Size((int)canvas.Width, (int)canvas.Height)));

            renderBitmap.Render(canvas);
            string extenstion = System.IO.Path.GetExtension(fileName);

            // TODO: fix this repetitive code
            if (extenstion.Contains(".png"))
            {
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(renderBitmap));

                using (System.IO.FileStream file = System.IO.File.Create(fileName))
                {
                    encoder.Save(file);
                }
            }
            else if (extenstion.Contains(".gif"))
            {
                GifBitmapEncoder encoder = new GifBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(renderBitmap));

                using (System.IO.FileStream file = System.IO.File.Create(fileName))
                {
                    encoder.Save(file);
                }
            }
            else if (extenstion.Contains(".tif"))
            {
                TiffBitmapEncoder encoder = new TiffBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(renderBitmap));

                using (System.IO.FileStream file = System.IO.File.Create(fileName))
                {
                    encoder.Save(file);
                }
            }
            else // JPEG for everything else
            {
                JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(renderBitmap));

                using (System.IO.FileStream file = System.IO.File.Create(fileName))
                {
                    encoder.Save(file);
                }
            }
        }