/// <summary>
        /// MatをBitmapSourceに変換する. 
        /// </summary>
        /// <param name="src">変換するIplImage</param>
        /// <param name="horizontalResolution"></param>
        /// <param name="verticalResolution"></param>
        /// <param name="pixelFormat"></param>
        /// <param name="palette"></param>
        /// <returns>WPFのBitmapSource</returns>
#else
        /// <summary>
        /// Converts Mat to BitmapSource.
        /// </summary>
        /// <param name="src">Input IplImage</param>
        /// <param name="horizontalResolution"></param>
        /// <param name="verticalResolution"></param>
        /// <param name="pixelFormat"></param>
        /// <param name="palette"></param>
        /// <returns>BitmapSource</returns>
#endif
        public static BitmapSource ToBitmapSource(
            this Mat src,
            int horizontalResolution,
            int verticalResolution,
            PixelFormat pixelFormat,
            BitmapPalette palette)
        {
            if (src == null)
                throw new ArgumentNullException("src");
            if (src.IsDisposed)
                throw new ObjectDisposedException(typeof(Mat).ToString());
            if (src.Dims() != 2)
                throw new ArgumentException("src.Dims() != 2");

            long step = src.Step();
            return BitmapSource.Create(
                src.Width,
                src.Height,
                horizontalResolution,
                verticalResolution,
                pixelFormat,
                palette,
                src.Data,
                (int)(step * src.Rows),
                (int)step);
        }
        //-----------------------------------------------------------------------------------------------
        //-----------------------------------------------------------------------------------------------
        //Создание WriteableBitmap
        public static WriteableBitmapWrapper Create(WriteableBitmap writeableBitmap)
        {
            media.PixelFormat format = writeableBitmap.Format;

            if (format == media.PixelFormats.Rgb48)
            {
                return(new WriteableBitmapWrapperRGB48(writeableBitmap));
            }

            if (format == media.PixelFormats.Rgba64)
            {
                return(new WriteableBitmapWrapperRGBA64(writeableBitmap));
            }
            if (format == media.PixelFormats.Bgra32)
            {
                return(new WriteableBitmapWrapperBGRA32(writeableBitmap));
            }
            if (format == media.PixelFormats.Gray16)
            {
                return(new WriteableBitmapWrapperGray16(writeableBitmap));
            }
            if (format == media.PixelFormats.Indexed8)
            {
                return(new WriteableBitmapWrapperIndexed8(writeableBitmap));
            }
            else
            {
                throw new ImageException();
            }
        }
Esempio n. 3
0
        private static void SaveBmp(Bitmap bmp, string path)
        {
            Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);

            BitmapData bitmapData = bmp.LockBits(rect, ImageLockMode.ReadOnly, bmp.PixelFormat);

            System.Windows.Media.PixelFormat pixelFormats = ConvertBmpPixelFormat(bmp.PixelFormat);
            pixelFormats = PixelFormats.Gray16;
            BitmapSource source = BitmapSource.Create(bmp.Width,
                                                      bmp.Height,
                                                      bmp.HorizontalResolution,
                                                      bmp.VerticalResolution,
                                                      pixelFormats,
                                                      null,
                                                      bitmapData.Scan0,
                                                      bitmapData.Stride * bmp.Height,
                                                      bitmapData.Stride);

            bmp.UnlockBits(bitmapData);


            FileStream stream = new FileStream(path, FileMode.Create);

            TiffBitmapEncoder encoder = new TiffBitmapEncoder();

            encoder.Compression = TiffCompressOption.Zip;
            encoder.Frames.Add(BitmapFrame.Create(source));
            encoder.Save(stream);

            stream.Close();
        }
        public static BitmapSource RenderToBitmap(
            this Visual visual,
            PixelFormat pixelFormat,
            FlowDirection flowDirection = FlowDirection.LeftToRight,
            double dpiX = 96.0,
            double dpiY = 96.0)
        {
            if (visual == null)
                throw new ArgumentException("visual");

            var cv = visual as ContainerVisual;
            if (cv != null)
            {
                var bounds = cv.DescendantBounds;

                var size = new Size(bounds.Right, bounds.Bottom);

                return visual.RenderToBitmap(size, bounds.Location, bounds.Size, pixelFormat);
            }
            else
            {
                var bounds = VisualTreeHelper.GetDescendantBounds(visual);

                var size = new Size(bounds.Right, bounds.Bottom);

                return visual.RenderToBitmap(size, bounds.Location, bounds.Size, pixelFormat);
            }
        }
Esempio n. 5
0
        public bool StartStream(string url)
        {
            ///Оборачиваем конструктор класса VideoCapture в задачу, и ждем завершения 5 секунд.
            ///Это необходимо, т.к. у VideoCapture нет таймаута и если камера не ответила, то приложение зависнет.
            var CaptureTask = Task.Factory.StartNew(() => Capture = new VideoCapture(url));

            if (!CaptureTask.Wait(new TimeSpan(0, 0, 5)))
            {
                return(false);
            }
            ///Получаем первый кадр с камеры
            Capture.Grab();
            ///Если удачно записали его в переменную, то продолжаем
            if (!Capture.Retrieve(MatFrame, 3))
            {
                return(false);
            }
            ///Узнаем формат пикселей кадра
            System.Windows.Media.PixelFormat pixelFormat = GetPixelFormat(MatFrame);
            ///Определяем сколько места занимает один кадр
            pcount = (uint)(MatFrame.Width * MatFrame.Height * pixelFormat.BitsPerPixel / 8);
            ///Создаем объект в памяти
            source = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, pcount, null);
            ///Получаем ссылку на начальный адрес объекта
            map = MapViewOfFile(source, 0xF001F, 0, 0, pcount);
            ///Инициализируем InteropBitmap используя созданный выше объект в памяти
            Frame = Imaging.CreateBitmapSourceFromMemorySection(source, MatFrame.Width, MatFrame.Height, pixelFormat, MatFrame.Width * pixelFormat.BitsPerPixel / 8, 0) as InteropBitmap;
            Capture.ImageGrabbed += Capture_ImageGrabbed;
            Capture.Start();
            return(true);
        }
Esempio n. 6
0
        /// <summary>
        /// Converts a depth frame to the corresponding System.Windows.Media.ImageSource.
        /// </summary>
        /// <param name="frame">The specified depth frame.</param>
        /// <param name="format">Pixel format of the depth frame.</param>
        /// <param name="mode">Depth frame mode.</param>
        /// <returns>The corresponding System.Windows.Media.ImageSource representation of the depth frame.</returns>
        public static ImageSource ToBitmap(this DepthImageFrame frame, PixelFormat format, DepthImageMode mode)
        {
            short[] pixelData = new short[frame.PixelDataLength];
            frame.CopyPixelDataTo(pixelData);

            byte[] pixels;

            switch (mode)
            {
                case DepthImageMode.Raw:
                    pixels = GenerateRawFrame(frame, pixelData);
                    break;
                case DepthImageMode.Dark:
                    pixels = GenerateDarkFrame(frame, pixelData);
                    break;
                case DepthImageMode.Colors:
                    pixels = GenerateColoredFrame(frame, pixelData);
                    break;
                case DepthImageMode.Player:
                    pixels = GeneratePlayerFrame(frame, pixelData);
                    break;
                default:
                    pixels = GenerateRawFrame(frame, pixelData);
                    break;
            }

            return pixels.ToBitmap(frame.Width, frame.Height, format);
        }
Esempio n. 7
0
        private void New_Click(object sender, RoutedEventArgs e) //新建白图
        {
            rectangle1.Visibility = Visibility.Hidden;
            drawingGroup1.Children.Clear();
            BitmapSource bitmap = BitmapSource.Create(1024, 800, 96, 96, PixelFormats.Pbgra32, null, array, 1024 * 4);//创建一个位图

            MyImageX      = bitmap.Width;
            MyImageY      = bitmap.Height;
            MyImagePixely = bitmap.PixelHeight;
            MyImagepixelX = bitmap.PixelWidth;
            MyImageDpiX   = bitmap.DpiX;
            MyImagedpiY   = bitmap.DpiY;
            image.Width   = bitmap.Width;
            image.Height  = bitmap.Height;
            MyPixelFormat = bitmap.Format;
            //上面是创建位图 下面因为是image 所以用image来绘制
            ImageDrawing imageDrawing = new ImageDrawing();

            imageDrawing.ImageSource = bitmap;
            drawingGroup1.Children.Add(imageDrawing);
            //绘制矩形
            RectangleGeometry rect = new RectangleGeometry();

            rect.Rect = new Rect(0, 0, 1024, 1024);    //创建一个抽象矩形
            GeometryDrawing g = new GeometryDrawing(); //用这个类来绘制

            g.Geometry = rect;
            g.Brush    = Brushes.White;
            Drawimage(g);
        }
 public static IEnumerable<ColorRGBA> GetPixels(byte[] pixelByteArray, PixelFormat pixelFormat)
 {
     if (pixelFormat == PixelFormats.Bgra32)
     {
         for (int i = 0; i < pixelByteArray.Length; i += 4)
         {
             yield return new ColorRGBA
             {
                 Blue = pixelByteArray[i],
                 Green = pixelByteArray[i + 1],
                 Red = pixelByteArray[i + 2],
                 Alpha = pixelByteArray[i + 3]
             };
         }
     }
     else if (pixelFormat == PixelFormats.Bgr32)
     {
         for (int i = 0; i < pixelByteArray.Length; i += 4)
         {
             yield return new ColorRGBA
             {
                 Blue = pixelByteArray[i],
                 Green = pixelByteArray[i + 1],
                 Red = pixelByteArray[i + 2],
                 Alpha = 255
             };
         }
     }
     else
     {
         yield break;
     }
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="geometry"></param>
        /// <param name="bitmapSize"></param>
        /// <param name="geometryPositionOnBitmap"></param>
        /// <param name="brush">The Brush with which to fill the Geometry. This is optional, and can be null. If the brush is null, no fill is drawn.</param>
        /// <param name="pen">The Pen with which to stroke the Geometry. This is optional, and can be null. If the pen is null, no stroke is drawn</param>
        /// <param name="pixelFormat"></param>
        /// <param name="dpiX"></param>
        /// <param name="dpiY"></param>
        /// <returns></returns>
        public static BitmapSource RenderToBitmap(
            this Geometry geometry,
            Size bitmapSize,
            Point geometryPositionOnBitmap,
            Size geometrySize,
            Brush brush,
            Pen pen,
            PixelFormat pixelFormat,
            double dpiX = 96.0,
            double dpiY = 96.0)
        {
            var rtb = new RenderTargetBitmap((int)(bitmapSize.Width * dpiX / 96.0),
                                             (int)(bitmapSize.Height * dpiY / 96.0),
                                             dpiX,
                                             dpiY,
                                             pixelFormat);

            var dv = new DrawingVisual();

            using (var cx = dv.RenderOpen())
            {
                cx.Render(geometry, geometryPositionOnBitmap, brush, pen);
            }

            rtb.Render(dv);

            return rtb;
        }
Esempio n. 10
0
        /// <summary>
        /// Given a bitmap, process the data into a render-able <see cref="BitmapSource"/>
        /// </summary>
        /// <param name="image">bitmap for image we want to make render-able</param>
        /// <returns>render-able image</returns>
        private static BitmapSource LoadImageBitmapSource(Bitmap image)
        {
            // Take the bitmap data and acquire a lock to it (no corrupt bits allowed here no sir!)
            BitmapData imageData =
                image.LockBits(
                    new Rectangle(0, 0, image.Width, image.Height),
                    ImageLockMode.ReadWrite,
                    image.PixelFormat);

            // This is here to support the case where not all shirt images follow the same
            // pixel format, which leads to bitmapsource creation being a pain
            System.Windows.Media.PixelFormat pixelFormat = PixelFormats.Bgra32;
            if (image.PixelFormat.Equals(System.Drawing.Imaging.PixelFormat.Format24bppRgb))
            {
                pixelFormat = PixelFormats.Bgr24;
            }

            // Copy the bitmap source to a render-able instance
            BitmapSource imageBitmap =
                BitmapSource.Create(
                    image.Width,
                    image.Height,
                    image.HorizontalResolution,
                    image.VerticalResolution,
                    pixelFormat,
                    null,
                    imageData.Scan0,
                    image.Width * image.Height * 4,
                    imageData.Stride);

            return(imageBitmap);
        }
Esempio n. 11
0
        private BitmapSource ToBitmap(ColorFrame frame)
        {
            int width  = frame.FrameDescription.Width;
            int height = frame.FrameDescription.Height;

            System.Windows.Media.PixelFormat format = PixelFormats.Bgr32;

            byte[] pixels = new byte[width * height * ((PixelFormats.Bgr32.BitsPerPixel + 7) / 8)];

            if (frame.RawColorImageFormat == ColorImageFormat.Bgra)
            {
                frame.CopyRawFrameDataToArray(pixels);
            }
            else
            {
                frame.CopyConvertedFrameDataToArray(pixels, ColorImageFormat.Bgra);
            }

            int               stride   = width * format.BitsPerPixel / 8;
            BitmapSource      bitmap   = BitmapSource.Create(width, height, 96, 96, format, null, pixels, stride);
            ScaleTransform    scale    = new ScaleTransform((1920.0 / bitmap.PixelWidth), (1080.0 / bitmap.PixelHeight));
            TransformedBitmap tbBitmap = new TransformedBitmap(bitmap, scale);


            return(tbBitmap);
        }
        /// <summary>
        /// Creates bitmap from short array
        /// </summary>
        /// <param name="visibleImage">Visible image buffer</param>
        /// <param name="width">Width in pixels</param>
        /// <param name="height">Height in pixels</param>
        /// <param name="pixelFormat">Pixel format</param>
        /// <returns>Bitmap source instance</returns>
        private static BitmapSource CreateBitmapSourceFromInfraredArray(
            byte[] visibleImage,
            int width,
            int height,
            swm.PixelFormat pixelFormat)
        {
            var ir = new short[visibleImage.Length / 2];

            // first convert the byte array to short and track max value
            short maxValue = 0;

            for (int i = 0; i < ir.Length; i++)
            {
                ir[i]    = (short)(visibleImage[i * 2] | (visibleImage[(i * 2) + 1] << 8));
                maxValue = Math.Max(maxValue, ir[i]);
            }

            // then rescale [0,maxValue] -> [0, ushort.Max]
            for (int i = 0; i < ir.Length; i++)
            {
                ir[i] = (short)((ushort.MaxValue * ir[i]) / maxValue);
            }

            var stride = (pixelFormat.BitsPerPixel / 8) * width;

            return(BitmapSource.Create(
                       width,
                       height,
                       96,
                       96,
                       pixelFormat,
                       null,
                       ir,
                       stride));
        }
Esempio n. 13
0
        /// <summary>
        /// Converts a color frame to a System.Media.ImageSource with its background removed.
        /// </summary>
        /// <param name="frame">A BackgroundRemovedColorFrame generated from a Kinect sensor.</param>
        /// <param name="format">The pixel format.</param>
        /// <returns>The specified frame in a System.media.ImageSource format.</returns>
        public static ImageSource ToBitmap(this BackgroundRemovedColorFrame frame, System.Windows.Media.PixelFormat format)
        {
            byte[] pixels = new byte[frame.PixelDataLength];
            frame.CopyPixelDataTo(pixels);

            return(pixels.ToBitmap(frame.Width, frame.Height, format));
        }
Esempio n. 14
0
        /// <summary>
        /// Ctor.
        /// </summary>
        /// <param name="format">The pixel format to use for conversion.</param>
        /// <param name="encoder">The encoder to use.</param>
        /// <param name="rotate">Degrees of rotation to apply (counterclock whise).</param>
        public BitmapSourceConverter(PixelFormat format, Encoder encoder, int rotate = 0)
        {
            _format = format;
            _encoder = encoder;

            Rotate = rotate;
        }
Esempio n. 15
0
        /// <summary> 
        /// Construct a ColorConvertedBitmap
        /// </summary>
        /// <param name="source">Input BitmapSource to color convert</param>
        /// <param name="sourceColorContext">Source Color Context</param> 
        /// <param name="destinationColorContext">Destination Color Context</param>
        /// <param name="format">Destination Pixel format</param> 
        public ColorConvertedBitmap(BitmapSource source, ColorContext sourceColorContext, ColorContext destinationColorContext, PixelFormat format) 
            : base(true) // Use base class virtuals
        { 
            if (source == null)
            {
                throw new ArgumentNullException("source");
            } 

            if (sourceColorContext == null) 
            { 
                throw new ArgumentNullException("sourceColorContext");
            } 

            if (destinationColorContext == null)
            {
                throw new ArgumentNullException("destinationColorContext"); 
            }
 
            _bitmapInit.BeginInit(); 

            Source = source; 
            SourceColorContext = sourceColorContext;
            DestinationColorContext = destinationColorContext;
            DestinationFormat = format;
 
            _bitmapInit.EndInit();
            FinalizeCreation(); 
        } 
Esempio n. 16
0
        /// <summary>
        /// 打开保存新建
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpenBtn_Click(object sender, RoutedEventArgs e)
        {
            rectangle1.Visibility = Visibility.Hidden;
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.Title  = "请打开图片";
            dialog.Filter = "图像文件 | *.jpg; *.png; *.jpeg; *.bmp; *.gif | 所有文件 | *.* ";
            if ((bool)dialog.ShowDialog())
            {
                //MessageBox.Show(drawingGroup1.Children.Count().ToString());
                {
                    image.Stretch = Stretch.UniformToFill;
                    drawingGroup1.Children.Clear();
                    BitmapFrame bf = BitmapFrame.Create(new Uri(dialog.FileName));
                    MyImageX      = bf.Width;
                    MyImageY      = bf.Height;
                    MyImagePixely = bf.PixelHeight;
                    MyImagepixelX = bf.PixelWidth;
                    MyImageDpiX   = bf.DpiX;
                    MyImagedpiY   = bf.DpiY;
                    image.Width   = bf.Width;
                    image.Height  = bf.Height;
                    MyPixelFormat = bf.Format;
                    ImageDrawing imageDrawing = new ImageDrawing();
                    imageDrawing.Rect        = new Rect(0, 0, bf.Width, bf.Height);
                    imageDrawing.ImageSource = bf;
                    Drawimage(imageDrawing);
                }
            }
        }
Esempio n. 17
0
        /// <summary>
        ///   Converts the given (System.Windows.Media.PixelFormat to its WPF (System.Drawing.Imaging) equivalent.
        /// </summary>
        ///
        public static System.Drawing.Imaging.PixelFormat ToImaging(this System.Windows.Media.PixelFormat pixelFormat)
        {
            if (pixelFormat == PixelFormats.Indexed8)
            {
                return(System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
            }
            if (pixelFormat == PixelFormats.Gray8)
            {
                return(System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
            }
            if (pixelFormat == PixelFormats.Bgr24)
            {
                return(System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            }
            if (pixelFormat == PixelFormats.Bgr32)
            {
                return(System.Drawing.Imaging.PixelFormat.Format32bppRgb);
            }
            if (pixelFormat == PixelFormats.Bgra32)
            {
                return(System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            }

            if (pixelFormat == PixelFormats.Gray32Float)
            {
                return(System.Drawing.Imaging.PixelFormat.Extended);
            }

            throw new NotImplementedException(String.Format("Conversion from pixel format {0} is not supported yet, please open a new ticket in Accord.NET's issue tracker.", pixelFormat));
        }
Esempio n. 18
0
        private static System.Windows.Media.PixelFormat ConvertBmpPixelFormat(System.Drawing.Imaging.PixelFormat pixelformat)
        {
            System.Windows.Media.PixelFormat pixelFormats = System.Windows.Media.PixelFormats.Default;

            switch (pixelformat)
            {
            case System.Drawing.Imaging.PixelFormat.Format32bppArgb:
                pixelFormats = PixelFormats.Bgr32;
                break;

            case System.Drawing.Imaging.PixelFormat.Format8bppIndexed:
                pixelFormats = PixelFormats.Gray8;
                break;

            case System.Drawing.Imaging.PixelFormat.Format16bppGrayScale:
                pixelFormats = PixelFormats.Gray16;
                break;

            case System.Drawing.Imaging.PixelFormat.Format64bppArgb:
                pixelFormats = PixelFormats.Rgba64;
                break;

            case System.Drawing.Imaging.PixelFormat.Format32bppRgb:
                pixelFormats = PixelFormats.Bgra32;
                break;
            }

            return(pixelFormats);
        }
Esempio n. 19
0
        public static ImageSource ToBitmap(this DepthFrame frame)
        {
            int width  = frame.FrameDescription.Width;
            int height = frame.FrameDescription.Height;

            System.Windows.Media.PixelFormat format = PixelFormats.Bgr32;
            ushort minDepth = frame.DepthMinReliableDistance;
            ushort maxDepth = frame.DepthMaxReliableDistance;

            ushort[] depthData = new ushort[width * height];
            byte[]   pixelData = new byte[width * height * (PixelFormats.Bgr32.BitsPerPixel + 7) / 8];

            frame.CopyFrameDataToArray(depthData);
            int colorIndex = 0;

            for (int depthIndex = 0; depthIndex < depthData.Length; ++depthIndex)
            {
                ushort depth     = depthData[depthIndex];
                byte   intensity = (byte)(depth >= minDepth && depth <= maxDepth ? depth : 0);

                pixelData[colorIndex++] = intensity; // blue
                pixelData[colorIndex++] = intensity; // green
                pixelData[colorIndex++] = intensity; // red

                ++colorIndex;
            }

            int stride = width * format.BitsPerPixel / 8;

            return(BitmapSource.Create(width, height, 96, 96, format, null, pixelData, stride));
        }
        private void GetMediaType(System.Windows.Media.PixelFormat pixelFormat, out Guid mediaSubType, out short bitCount)
        {
            //Very basic implementation, should look how to convert
            //"System.Drawing.Imaging.PixelFormat to "System.Windows.Media.PixelFormat"

            switch (pixelFormat.BitsPerPixel)
            {
            case 32:
                bitCount     = 32;
                mediaSubType = MediaSubType.RGB32;
                break;

            case 24:
                bitCount     = 24;
                mediaSubType = MediaSubType.RGB24;
                break;

            case 16:
                bitCount     = 16;
                mediaSubType = MediaSubType.RGB565;
                break;

            default:
                throw new Exception("Unrecognized Pixelformat in bitmap");
            }
        }
        public static IBitmapSourceGrayScaleConverter GetConverter(PixelFormat format)
        {
            if (format == PixelFormats.Bgra32 || format == PixelFormats.Bgr32)
                return BgrGrayScaleConverter.Instance;


            throw new NotSupportedException(string.Format("PixelFormat {0} is not supported", format.GetType().Name));
        }
Esempio n. 22
0
 public RenderedBitmap(int width, int height, int stride, PixelFormat format, byte[] bits)
 {
     this.width = width;
       this.height = height;
       this.stride = stride;
       this.format = format;
       this.bits = bits;
 }
 /// <summary>
 /// Конвертация BitmapSource в другой формат BitmapSource.
 /// </summary>
 /// <param name="source">Источник для конвертации.</param>
 /// <param name="destinationFormat">Новый формат.</param>
 /// <param name="destinationPalette">
 /// Палитра для нового формата, если конечно она нужна для нового формата, иначе передать null.
 /// </param>
 /// <returns>BitmapSource в новом формате.</returns>
 public static BitmapSource ConvertTo(
     this BitmapSource source,
     PixelFormat destinationFormat,
     BitmapPalette destinationPalette)
 {
     return new FormatConvertedBitmap(
         source, destinationFormat, destinationPalette, 0);
 }
 /// <summary>
 /// Конвертация BitmapSource в другой формат BitmapSource.
 /// </summary>
 /// <param name="source">Источник для конвертации.</param>
 /// <param name="destinationFormat">Новый формат.</param>
 /// <param name="destinationPalette">
 /// Палитра для нового формата, если конечно она нужна для нового формата, иначе передать null.
 /// </param>
 /// <returns>BitmapSource в новом формате.</returns>
 public static BitmapSource ConvertTo(
     this BitmapSource source,
     PixelFormat destinationFormat,
     BitmapPalette destinationPalette)
 {
     return(new FormatConvertedBitmap(
                source, destinationFormat, destinationPalette, 0));
 }
Esempio n. 25
0
 /// <summary>
 /// Returns the data Type (float or Int) of PixelFormat Type.
 /// </summary>
 /// <param name="pixelFormat"></param>
 /// <returns></returns>
 public static Type GetType(this System.Windows.Media.PixelFormat pixelFormat)
 {
     if (!DiscreteTypeDictionary.ContainsKey(pixelFormat))
     {
         throw new NotSupportedException("Type: " + pixelFormat + " is not supported by DiscreteTypeDictionary");
     }
     return(DiscreteTypeDictionary[pixelFormat]);
 }
Esempio n. 26
0
 public static bool HasAlpha(this swm.PixelFormat format)
 {
     return(format == swm.PixelFormats.Pbgra32 ||
            format == swm.PixelFormats.Prgba128Float ||
            format == swm.PixelFormats.Prgba64 ||
            format == swm.PixelFormats.Rgba64 ||
            format == swm.PixelFormats.Rgba64);
 }
Esempio n. 27
0
 public MapUpdatedEventArgs(byte[] map, int xres, int yres, int stride, PixelFormat format)
 {
     this.Map = map;
     this.XRes = xres;
     this.YRes = yres;
     this.Stride = stride;
     this.Format = format;
 }
        private static BitmapSource BitmapToBitmapSource(Bitmap bitmap, System.Windows.Media.PixelFormat pixelFormat)
        {
            var bitmapData   = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
            var bitmapSource = BitmapSource.Create(bitmapData.Width, bitmapData.Height, 96, 96, pixelFormat, null, bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride);

            bitmap.UnlockBits(bitmapData);
            return(bitmapSource);
        }
Esempio n. 29
0
 public static Bitmap ToBitmap(this DepthImageFrame image, PixelFormat format)
 {
     if (image == null || image.PixelDataLength == 0)
         return null;
     var data = new short[image.PixelDataLength];
     image.CopyPixelDataTo(data);
     return data.ToBitmap(image.Width, image.Height
         , format);
 }
Esempio n. 30
0
 /// <summary>
 /// Returns the compatible type of System.Drawing.Imaging.PixelFormat for a given System.Windows.Media.PixelFormat.
 /// </summary>
 /// <param name="pixelFormat"></param>
 /// <returns></returns>
 public static System.Drawing.Imaging.PixelFormat ToDrawingPixelFormat(
     this System.Windows.Media.PixelFormat pixelFormat)
 {
     if (!PixelFormatDictionary.ContainsKey(pixelFormat))
     {
         throw new NotSupportedException("Type: " + pixelFormat + " is not supported by PixelFormatDictionary.");
     }
     return(PixelFormatDictionary[pixelFormat]);
 }
Esempio n. 31
0
 public ImageContext(int h, int w, PixelFormat f)
 {
     Height = h;
     Width = w;
     ImageFormat = f;
     NStride = (Width * ImageFormat.BitsPerPixel + 7) / 8;
     PixelByteArraySize = Height * NStride;
     PixelByteArray = new byte[PixelByteArraySize];
 }
 public VlcControlWpfRendererContext(int width, int height, PixelFormat format)
 {
     Size = width * height * format.BitsPerPixel / 8;
     Data = Marshal.AllocHGlobal(Size);
     Width = width;
     Height = height;
     PixelFormat = format;
     Stride = width * format.BitsPerPixel / 8;
 }
Esempio n. 33
0
 public static BitmapImage ConvertToOtherPixelFormat(BitmapSource source, PixelFormat format)
 {
     var newFormatedBitmapSource = new FormatConvertedBitmap();
     newFormatedBitmapSource.BeginInit();
     newFormatedBitmapSource.Source = source;
     newFormatedBitmapSource.DestinationFormat = format;
     newFormatedBitmapSource.EndInit();
     return BitmapSourceToBitmapImage(newFormatedBitmapSource.Source);
 }
        /// <summary>
        /// MatをBitmapSourceに変換する. 
        /// </summary>
        /// <param name="src">変換するIplImage</param>
        /// <param name="horizontalResolution"></param>
        /// <param name="verticalResolution"></param>
        /// <param name="pixelFormat"></param>
        /// <param name="palette"></param>
        /// <returns>WPFのBitmapSource</returns>
#else
        /// <summary>
        /// Converts Mat to BitmapSource.
        /// </summary>
        /// <param name="src">Input IplImage</param>
        /// <param name="horizontalResolution"></param>
        /// <param name="verticalResolution"></param>
        /// <param name="pixelFormat"></param>
        /// <param name="palette"></param>
        /// <returns>BitmapSource</returns>
#endif
        public static BitmapSource ToBitmapSource(
            this Mat src,
            int horizontalResolution,
            int verticalResolution,
            PixelFormat pixelFormat,
            BitmapPalette palette)
        {
            return src.ToWriteableBitmap(horizontalResolution, verticalResolution, pixelFormat, palette);
        }
Esempio n. 35
0
 /// <summary>Captures a snapshot of the source element as a bitmap image. The snapshot is created based on the specified rendering parameters.</summary>
 /// <param name="sourceElement">The source element.</param>
 /// <param name="bitmapSize">The bitmap size.</param>
 /// <param name="scalingMode">The bitmap scaling mode.</param>
 /// <param name="bitmapDpi">The bitmap dpi.</param>
 /// <param name="pixelFormat">The bitmap pixel format.</param>
 /// <returns>The snapshot of the source element.</returns>
 public static BitmapSource CaptureSnapshot(FrameworkElement sourceElement, Size bitmapSize, BitmapScalingMode scalingMode, Vector bitmapDpi, PixelFormat pixelFormat) {
    if (sourceElement == null || bitmapSize.IsZero()) return null;
    var snapshot = new RenderTargetBitmap((int)bitmapSize.Width, (int)bitmapSize.Height, bitmapDpi.X, bitmapDpi.Y, pixelFormat);
    sourceElement.SetValue(RenderOptions.BitmapScalingModeProperty, scalingMode);
    snapshot.Render(sourceElement);
    sourceElement.ClearValue(RenderOptions.BitmapScalingModeProperty);
    snapshot.Freeze();
    return snapshot;
 }
Esempio n. 36
0
        public static Bitmap SharedImageToBitmap(Shared <Image> input)
        {
            PixelFormat     pixelFormat = SharedImageToPixelFormat(input);
            WriteableBitmap VideoImage  = new WriteableBitmap(input.Resource.Width, input.Resource.Height, 300, 300, pixelFormat, null);

            VideoImage.WritePixels(new Int32Rect(0, 0, input.Resource.Width, input.Resource.Height), input.Resource.ImageData, input.Resource.Stride * input.Resource.Height, input.Resource.Stride);
            Bitmap VideoImageBitmap = BitmapFromWriteableBitmap(VideoImage);

            return(VideoImageBitmap);
        }
Esempio n. 37
0
        private static System.Drawing.Imaging.PixelFormat GetBitmapPixelFormat(System.Windows.Media.PixelFormat bitmapSourcePixelFormat)
        {
            if (!PixelFormatTranslator.ContainsValue(bitmapSourcePixelFormat))
            {
                throw new ArgumentOutOfRangeException("bitmapSourcePixelFormat", bitmapSourcePixelFormat,
                                                      "Unsupported pixel format.");
            }

            return(PixelFormatTranslator.Single(kv => kv.Value == bitmapSourcePixelFormat).Key);
        }
Esempio n. 38
0
        /// <summary>
        /// MilImage ==> byte array 변환기.
        /// </summary>
        /// <param name="matImage">MIL 이미지.</param>
        /// <returns></returns>
        public static byte[] MilImageToBuffer(MilImage milImage, System.Windows.Media.PixelFormat Format)
        {
            byte[] buffer = new byte[milImage.GetBufferSize()];

            milImage.GetColor((Format.BitsPerPixel / 8), buffer);

            System.Drawing.Size imageSize = (System.Drawing.Size)milImage.GetImageSize();

            return(buffer);
        }
Esempio n. 39
0
        private object[] ReadOptions()
        {
            // TODO parse input options
            _width  = UtilApplication.ParseAsInt(TextBoxWidth.Text, 1);
            _height = UtilApplication.ParseAsInt(TextBoxHeight.Text, 1);
            _dpi    = 96;
            _format = System.Windows.Media.PixelFormats.Bgra32;

            return(new object[] { _width, _height, _dpi, _format });
        }
Esempio n. 40
0
        public static BitmapSource setPixelFormat1(BitmapSource image, System.Windows.Media.PixelFormat format)
        {
            var formatted = new FormatConvertedBitmap();

            formatted.BeginInit();
            formatted.Source            = image;
            formatted.DestinationFormat = format;
            formatted.EndInit();
            return(formatted);
        }
Esempio n. 41
0
 public Bitmap2D(long width, long height, PixelFormat pf)
     : base()
 {
     pixelFormat = pf;
     bitmapWidth = width;
     bitmapHeight = height;
     totalNumberPixels = bitmapWidth * bitmapHeight;
     maxSize = totalNumberPixels * pixelFormat.BitsPerPixel / 8;
     pixelData = new byte[maxSize];
     whiteOutBitmap();
 }
Esempio n. 42
0
        public static void SaveImage(this UIElement element, Size size, PixelFormat pixelFormat, string fileName)
        {
            using var stream = File.OpenWrite(fileName);
            element.Measure(size);
            element.Arrange(new Rect(size));
            var renderTargetBitmap = element.ToRenderTargetBitmap(size, pixelFormat);
            var encoder            = GetEncoder(fileName);

            encoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
            encoder.Save(stream);
        }
Esempio n. 43
0
        public static BitmapSource Stretch(IImageStatistics statistics, Bitmap img, System.Windows.Media.PixelFormat pf, double factor, double blackClipping)
        {
            using (MyStopWatch.Measure()) {
                var filter = ImageUtility.GetColorRemappingFilter(statistics, factor, blackClipping, pf);
                filter.ApplyInPlace(img);

                var source = ImageUtility.ConvertBitmap(img, pf);
                source.Freeze();
                return(source);
            }
        }
 /// <summary>
 /// 指定したPixelFormatに適合するIplImageのチャンネル数を返す
 /// </summary>
 /// <param name="f"></param>
 /// <returns></returns>
 internal static int GetOptimumChannels(PixelFormat f)
 {
     try
     {
         return optimumChannels[f];
     }
     catch (KeyNotFoundException)
     {
         throw new ArgumentException("Not supported PixelFormat");
     }
 }
Esempio n. 45
0
        public void RecalcCanvas(System.Drawing.Imaging.PixelFormat format)
        {
            // TODO get format by url ending / mime type?
            _format = UtilDrawing.ConvertPixelFormat(format);

            // Calculate the number of bytes per pixel.
            _bytesPerPixel = (_format.BitsPerPixel + 7) / 8;

            // Stride is bytes per pixel times the number of pixels.
            // Stride is the byte width of a single rectangle row.
            _stride = _width * _bytesPerPixel;
        }
 public DrawingSettings(int pixelWidth, int pixelHeight, double dpiX, double dpiY,
     PixelFormat pixelFormat,
     BitmapPalette palette, int stride)
 {
     PixelWidth = pixelWidth;
     PixelHeight = pixelHeight;
     DpiX = dpiX;
     DpiY = dpiY;
     PixelFromatUsed = pixelFormat;
     BitmapPalleteUsed = palette;
     Stride = stride;
 }
        /// <summary>
        /// Convert bmpSource to format declared in pixFormat.
        /// </summary>
        /// <param name="bmpSource"></param>
        /// <param name="pixFormat"></param>
        /// <returns></returns>
        public static FormatConvertedBitmap BitmapToFormat(BitmapSource bmpSource,
                                           PixelFormat pixFormat)
        {
            if (bmpSource == null) { return null; }
            FormatConvertedBitmap fcb = new FormatConvertedBitmap();

            fcb.BeginInit();
            fcb.Source = bmpSource;
            fcb.DestinationFormat = pixFormat;
            fcb.EndInit();
            return fcb;
        }
Esempio n. 48
0
        public static Bitmap ToBitmap(this short[] data, int width, int height
            , PixelFormat format)
        {
            var bitmap = new Bitmap(width, height, format);

            var bitmapData = bitmap.LockBits(
                new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
                ImageLockMode.WriteOnly,
                bitmap.PixelFormat);
            Marshal.Copy(data, 0, bitmapData.Scan0, data.Length);
            bitmap.UnlockBits(bitmapData);
            return bitmap;
        }
Esempio n. 49
0
        public static BitmapSource ConvertBitmap(System.Drawing.Bitmap bitmap, System.Windows.Media.PixelFormat pf)
        {
            var bitmapData = bitmap.LockBits(
                new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
                System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat);

            var bitmapSource = BitmapSource.Create(
                bitmapData.Width, bitmapData.Height, 96, 96, pf, null,
                bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride);

            bitmap.UnlockBits(bitmapData);
            return(bitmapSource);
        }
        public InteropBitmapHelper(int width, int height, byte[] imageBits, PixelFormat pixelFormat)
        {
            _Width = width;
            _Height = height;
            _PixelFormat = pixelFormat;

            int stride = width * pixelFormat.BitsPerPixel / 8;
            _ColorByteCount = (uint)(height * stride);
            var colorFileMapping = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, _ColorByteCount, null);
            _ImageBits = MapViewOfFile(colorFileMapping, 0xF001F, 0, 0, _ColorByteCount);
            Marshal.Copy(imageBits, 0, _ImageBits, (int)_ColorByteCount);
            InteropBitmap = Imaging.CreateBitmapSourceFromMemorySection(colorFileMapping, width, height, pixelFormat, stride, 0) as InteropBitmap;
        }
Esempio n. 51
0
 public StarDetection(IRenderedImage renderedImage, System.Windows.Media.PixelFormat pf, StarSensitivityEnum sensitivity, NoiseReductionEnum noiseReduction)
     : this(renderedImage, sensitivity, noiseReduction)
 {
     if (pf == PixelFormats.Rgb48)
     {
         using (var source = ImageUtility.BitmapFromSource(_originalBitmapSource, System.Drawing.Imaging.PixelFormat.Format48bppRgb)) {
             using (var img = new Grayscale(0.2125, 0.7154, 0.0721).Apply(source)) {
                 _originalBitmapSource = ImageUtility.ConvertBitmap(img, System.Windows.Media.PixelFormats.Gray16);
                 _originalBitmapSource.Freeze();
             }
         }
     }
 }
Esempio n. 52
0
        public static System.Drawing.Imaging.PixelFormat ConvertPixelFormat2(System.Windows.Media.PixelFormat sourceFormat)
        {
            switch (sourceFormat.BitsPerPixel)
            {
            case 24:
                return(System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            case 32:
                return(System.Drawing.Imaging.PixelFormat.Format32bppRgb);

                // .. as many as you need...
            }
            return(new System.Drawing.Imaging.PixelFormat());
        }
Esempio n. 53
0
        public RenderTargetBitmap( 
            int pixelWidth, 
            int pixelHeight,
            double dpiX, 
            double dpiY,
            PixelFormat pixelFormat
            ) : base(true)
        { 
            if (pixelFormat.Format == PixelFormatEnum.Default)
            { 
                pixelFormat = PixelFormats.Pbgra32; 
            }
            else if (pixelFormat.Format != PixelFormatEnum.Pbgra32) 
            {
                throw new System.ArgumentException(
                        SR.Get(SRID.Effect_PixelFormat, pixelFormat),
                        "pixelFormat" 
                        );
            } 
 
            if (pixelWidth <= 0)
            { 
                throw new ArgumentOutOfRangeException("pixelWidth", SR.Get(SRID.ParameterMustBeGreaterThanZero));
            }

            if (pixelHeight <= 0) 
            {
                throw new ArgumentOutOfRangeException("pixelHeight", SR.Get(SRID.ParameterMustBeGreaterThanZero)); 
            } 

            if (dpiX < DoubleUtil.DBL_EPSILON) 
            {
                dpiX = 96.0;
            }
 
            if (dpiY < DoubleUtil.DBL_EPSILON)
            { 
                dpiY = 96.0; 
            }
 
            _bitmapInit.BeginInit();
            _pixelWidth = pixelWidth;
            _pixelHeight = pixelHeight;
            _dpiX = dpiX; 
            _dpiY = dpiY;
            _format = pixelFormat; 
            _bitmapInit.EndInit(); 
            FinalizeCreation();
        } 
        /// <summary>
        /// Convert bmpSource to format declared in pixFormat.
        /// </summary>
        /// <param name="bmpSource"></param>
        /// <param name="pixFormat"></param>
        /// <returns></returns>
        public static FormatConvertedBitmap BitmapToFormat(BitmapSource bmpSource,
                                                           PixelFormat pixFormat)
        {
            if (bmpSource == null)
            {
                return(null);
            }
            FormatConvertedBitmap fcb = new FormatConvertedBitmap();

            fcb.BeginInit();
            fcb.Source            = bmpSource;
            fcb.DestinationFormat = pixFormat;
            fcb.EndInit();
            return(fcb);
        }
Esempio n. 55
0
        public FluentBitmap(int pixelWidth, int pixelHeight, PixelFormat pixelFormat)
        {
            if (pixelFormat == null)
                throw new ArgumentNullException("pixelFormat", "pixelFormat is null.");
            if (pixelWidth <= 0)
                throw new ArgumentOutOfRangeException("pixelWidth", "pixelWidth must be greater than 0.");
            if (pixelHeight <= 0)
                throw new ArgumentOutOfRangeException("pixelHeight", "pixelHeight must be greater than 0.");

            PixelWidth = pixelWidth;
            PixelHeight = pixelHeight;
            PixelFormat = pixelFormat;
            StrideBytes = GetMinimumStride(pixelWidth, pixelFormat);
            PixelsPerInch = 96;
        }
        /// <summary>
        /// Строит пиксель по заданному адресу в памяти и формату
        /// </summary>
        /// <param name="pixelAddr">Адрес начала пикселя</param>
        /// <param name="format">Формат пикселя</param>
        /// <returns>Тип реализующий интерфейс IPixel или null если не существует реализации для указанного формата</returns>
        public unsafe IPixel CreatePixel(byte* pixelAddr, PixelFormat format)
        {
            if (PixelFormats.Bgra32.Equals(format))
                return new BGRA32PixelUnsafe(pixelAddr);

            if (PixelFormats.Bgr24.Equals(format))
                return new BGR24PixelUnsafe(pixelAddr);

            if (PixelFormats.Rgb24.Equals(format))
                return new RGB24PixelUnsafe(pixelAddr);

            if (PixelFormats.Bgr32.Equals(format))
                return new BGR24PixelUnsafe(pixelAddr);

            return null;
        }
Esempio n. 57
0
 /// <summary>
 /// Create a BitmapSource from an array of pixels.
 /// </summary>
 /// <param name="pixelWidth">Width of the Bitmap</param>
 /// <param name="pixelHeight">Height of the Bitmap</param>
 /// <param name="dpiX">Horizontal DPI of the Bitmap</param>
 /// <param name="dpiY">Vertical DPI of the Bitmap</param>
 /// <param name="pixelFormat">Format of the Bitmap</param>
 /// <param name="palette">Palette of the Bitmap</param>
 /// <param name="pixels">Array of pixels</param>
 /// <param name="stride">stride</param>
 public static BitmapSource Create(
     int pixelWidth,
     int pixelHeight,
     double dpiX,
     double dpiY,
     PixelFormat pixelFormat,
     Imaging.BitmapPalette palette,
     System.Array pixels,
     int stride
     )
 {
     return new CachedBitmap(
                 pixelWidth, pixelHeight,
                 dpiX, dpiY,
                 pixelFormat, palette,
                 pixels, stride);
 }
Esempio n. 58
0
        public void MakeBitmap()
        {
            BitmapImage myBitmapImage = new BitmapImage();
            myBitmapImage.BeginInit();
            myBitmapImage.UriSource = new Uri(@text1.Text);
            myBitmapImage.EndInit();
            myImage.Source = myBitmapImage;
            //
            height = myBitmapImage.PixelHeight;
            width = myBitmapImage.PixelWidth;
            imageFormat = myBitmapImage.Format;
            nStride = (myBitmapImage.PixelWidth * imageFormat.BitsPerPixel + 7) / 8;

            pixelByteArraySize = myBitmapImage.PixelHeight * nStride;
            pixelByteArrayIn = new byte[pixelByteArraySize];
            myBitmapImage.CopyPixels(pixelByteArrayIn, nStride, 0);
        }
Esempio n. 59
0
        private static bool TryGetComponentCount(PixelFormat format, out int componentCount)
        {
            // For this sample: only RGB color and 8 bit monochrome images are supported.
            if (format == PixelFormats.Bgr24)
            {
                componentCount = 3;
            }
            else if (format == PixelFormats.Gray8)
            {
                componentCount = 1;
            }
            else
            {
                componentCount = 0;
            }

            return componentCount != 0;
        }
Esempio n. 60
0
        unsafe internal CachedBitmap(
                    int pixelWidth,
                    int pixelHeight,
                    double dpiX,
                    double dpiY,
                    PixelFormat pixelFormat,
                    BitmapPalette palette,
                    IntPtr buffer,
                    int bufferSize,
                    int stride
                    )

            : base(true) // Use base class virtuals
        {
            InitFromMemoryPtr(pixelWidth, pixelHeight, dpiX, dpiY,
                              pixelFormat, palette,
                              buffer, bufferSize, stride);
        }