using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media.Imaging; namespace Tango.ScreenCapture { public class ScreenCaptureFrame : IDisposable { private Bitmap _bitmap; private Bitmap _diffBitmap; public int Width { get { return _bitmap.Width; } } public int Height { get { return _bitmap.Height; } } public bool HasDifferenceFrame { get { return _diffBitmap != null; } } public ScreenCaptureFrame(Bitmap bitmap, Bitmap diffBitmap) { _diffBitmap = diffBitmap; _bitmap = bitmap; } public void Dispose() { _bitmap.Dispose(); if (_diffBitmap != null) { _diffBitmap.Dispose(); } } public BitmapSource ToBitmapSource() { var source = GetBitmapImage(ToStream()); source.Freeze(); return source; } public Bitmap ToBitmap() { return _bitmap; } public ScreenCaptureFrame ToDifferenceCaptureFrame() { return new ScreenCaptureFrame(_diffBitmap, null); } public byte[] ToArray() { using (var ms = ToStream()) { return ms.ToArray(); } } public byte[] ToJpeg(int quality = 100) { var encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); using (MemoryStream ms = new MemoryStream()) { _bitmap.Save(ms, GetEncoder(ImageFormat.Jpeg), encoderParameters); ms.Position = 0; return ms.ToArray(); } } public byte[] ToPng() { using (MemoryStream ms = new MemoryStream()) { _bitmap.Save(ms, ImageFormat.Png); ms.Position = 0; return ms.ToArray(); } } public MemoryStream ToStream() { MemoryStream ms = new MemoryStream(); _bitmap.Save(ms, ImageFormat.Bmp); ms.Position = 0; return ms; } private BitmapImage GetBitmapImage(MemoryStream ms) { var bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = ms; bitmapImage.EndInit(); return bitmapImage; } private ImageCodecInfo GetEncoder(ImageFormat format) { ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders(); return codecs.Single(codec => codec.FormatID == format.Guid); } } }