Example #1
0
        private Image Output()
        {
            gl.Flush();
            gl.Blit(IntPtr.Zero);
            var provider = gl.RenderContextProvider as FBORenderContextProvider;
            //  TODO: We have to remove the alpha channel - for some reason it comes out as 0.0
            //  meaning the drawing comes out transparent.
            var newFormatedBitmapSource = new FormatConvertedBitmap();

            if (provider == null)
            {
                return(null);
            }
            newFormatedBitmapSource.BeginInit();
            newFormatedBitmapSource.Source            = BitmapConversion.HBitmapToBitmapSource(provider.InternalDIBSection.HBitmap);
            newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24;
            newFormatedBitmapSource.EndInit();

            var           outStream = new MemoryStream();
            BitmapEncoder enc       = new BmpBitmapEncoder();

            enc.Frames.Add(BitmapFrame.Create(newFormatedBitmapSource));
            enc.Save(outStream);
            //Console.ReadLine();

            //gl.Flush();
            //Console.ReadLine();
            return(new Bitmap(outStream));
        }
Example #2
0
        //-------------------------------------------------------------------
        // Constructor
        //-------------------------------------------------------------------
        public DrawDevice()
        {
            m_hwnd       = IntPtr.Zero;
            m_pDevice    = null;
            m_pSwapChain = null;

            m_d3dpp = null;
            m_Data  = IntPtr.Zero;

            m_format              = Format.X8R8G8B8;
            m_width               = 0;
            m_height              = 0;
            m_lDefaultStride      = 0;
            m_PixelAR.Denominator = m_PixelAR.Numerator = 1;
            m_rcDest              = Rectangle.Empty;

            VideoFormatDefs = new VideoFormatGUID[] {
                new VideoFormatGUID(MFMediaType.RGB32, TransformImage_RGB32, ARGB32_To_RGB32),
                new VideoFormatGUID(MFMediaType.RGB24, TransformImage_RGB24, ARGB32_To_RGB24),
                new VideoFormatGUID(MFMediaType.YUY2, TransformImage_YUY2, ARGB32_To_YUY2),
                new VideoFormatGUID(MFMediaType.NV12, TransformImage_NV12, ARGB32_To_NV12)
            };

            m_convertFn    = null;
            m_bmpconvertFn = null;
        }
        public static BitmapImage LowPerformance(Bitmap tempBmp, Bitmap resultBmp, MeasureTime measure)
        {
            int threshold = OtsuValue(tempBmp);   //calculate threshold by otsu value
            var stopwatch = Stopwatch.StartNew(); //start measure time

            int[] pixelValue = new int[tempBmp.Width + 1];

            for (int y = 0; y < tempBmp.Height; y++)
            {
                for (int x = 0; x < tempBmp.Width; x++)
                {
                    Color color = tempBmp.GetPixel(x, y);
                    pixelValue[x] = (color.R + color.G + color.B) / 3;

                    if (pixelValue[x] < threshold)
                    {
                        pixelValue[x] = 0;
                    }

                    else
                    {
                        pixelValue[x] = 255;
                    }

                    Color newColor = Color.FromArgb(pixelValue[x], pixelValue[x], pixelValue[x]);
                    resultBmp.SetPixel(x, y, newColor);
                }
            }

            measure.TimeElapsedMs = stopwatch.ElapsedMilliseconds;
            return(BitmapConversion.Bitmap2BitmapImage(resultBmp));
        }
Example #4
0
        public BitmapImage LoadAnimationTexture(string fileName, bool transparent = false)
        {
            if (transparent)
            {
                FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                System.Drawing.Bitmap img = new System.Drawing.Bitmap(fileStream);
                fileStream.Close();
                var color = img.Palette.Entries[0];
                string hex = HexConverter(color);
                Instance.ViewModel.SpriteSheetTransparentColors.Add((Color)ColorConverter.ConvertFromString(hex));
                img.MakeTransparent(color);
                return (BitmapImage)BitmapConversion.ToWpfBitmap(img);
            }
            else
            {
                FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);

                var img = new System.Windows.Media.Imaging.BitmapImage();
                img.BeginInit();
                img.StreamSource = fileStream;
                img.EndInit();
                return img;
            }

        }
Example #5
0
 private void ButtonCaptureHandler(object sender, RoutedEventArgs e)
 {
     try
     {
         var bitmap = WebCamCoreControl.GetCurrentImage();
         var repo   = DataContext as TrainingViewModel;
         if (repo != null)
         {
             if (repo.Repository == null)
             {
                 repo.Repository = new Models.RepositoryModel();
             }
             repo.Repository.UserID = Global.LoggedUser.ID;
             repo.Repository.Image  = BitmapConversion.BitmapToBitmapSource(bitmap);
             using (MemoryStream ms = new MemoryStream())
             {
                 ms.Position = 0;
                 bitmap.Save(ms, ImageFormat.Png);
                 ms.Position = 0;
                 repo.Repository.SampleImage = ms.ToArray();
             }
         }
     }
     catch (Exception ex)
     {
         LogHelper.LogException(new string[] { ex.Message });
     }
 }
Example #6
0
        public static BitmapImage Init(Bitmap resultBmp, MeasureTime measure)
        {
            var stopwatch = Stopwatch.StartNew();

            int[,] pixelArray = new int[resultBmp.Height, resultBmp.Width]; // one record on this array = one pixel

            pixelArray = LowPerformance.SetOneZero(resultBmp, pixelArray);

            deletion = 1;
            int deletionFirst, deletionSecond;

            while (deletion != 0)
            {
                deletion = 0;

                pixelArray = LowPerformance.SetOneTwoThree(resultBmp, pixelArray);
                (deletionFirst, pixelArray)  = LowPerformance.FindAndDeleteFour(resultBmp, pixelArray);
                (deletionSecond, pixelArray) = LowPerformance.DeletingTwoThree(resultBmp, pixelArray);

                deletion = deletionFirst > deletionSecond ? deletionFirst : deletionSecond;
            }

            resultBmp = LowPerformance.SetImageAfterKMM(resultBmp, pixelArray);

            measure.SumTimeElapsedMs(stopwatch.ElapsedMilliseconds);
            return(BitmapConversion.Bitmap2BitmapImage(resultBmp));
        }
Example #7
0
        public void Render()
        {
            _gl.MakeCurrent();
            _gl.ClearColor(0.2f, 0.2f, 0.2f, 0);
            _gl.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT);

            _gl.LoadIdentity();

            if (RenderScene != null)
            {
                RenderScene(this, new SimpleOpenGlEventArgs
                {
                    OpenGl = _gl
                });
            }

            _gl.Blit(IntPtr.Zero);

            var fboRenderContextProvider = (FBORenderContextProvider)_gl.RenderContextProvider;

            var formatConvertedBitmap = new FormatConvertedBitmap();

            formatConvertedBitmap.BeginInit();
            formatConvertedBitmap.Source            = BitmapConversion.HBitmapToBitmapSource(fboRenderContextProvider.InternalDIBSection.HBitmap);
            formatConvertedBitmap.DestinationFormat = PixelFormats.Rgb24;
            formatConvertedBitmap.EndInit();

            OpenGlImage.Source = formatConvertedBitmap;
        }
Example #8
0
        public override ImageSource Render()
        {
            GL.MakeCurrent();

            GL.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT);
            GL.ClearColor(1f, 0f, 0f, 0f);

            _postProcesser.Capture(() =>
            {
                GL.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT);
                _backgroundRenderer.Render();
                _octreeRenderer.Render();
            });

            _postProcesser.Render();

            GL.Blit(IntPtr.Zero);
            var provider = GL.RenderContextProvider as FBORenderContextProvider;

            if (provider == null)
            {
                return(null);
            }

            var newFormatedBitmapSource = new FormatConvertedBitmap();

            newFormatedBitmapSource.BeginInit();
            newFormatedBitmapSource.Source            = BitmapConversion.HBitmapToBitmapSource(provider.InternalDIBSection.HBitmap);
            newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24;
            newFormatedBitmapSource.EndInit();
            return(newFormatedBitmapSource);
        }
        public FormatConvertedBitmap GetFrame()
        {
            lock (Gl)
            {
                //  Render.
                Gl.Blit(IntPtr.Zero);

                IntPtr hBitmap = IntPtr.Zero;
                FormatConvertedBitmap newFormatedBitmapSource = null;
                switch (RenderContextType)
                {
                case RenderContextType.DIBSection:
                {
                    var provider = Gl.RenderContextProvider as DIBSectionRenderContextProvider;
                    //hBitmap = provider.DIBSection.HBitmap;
                    //break;
                    //  TODO: We have to remove the alpha channel - for some reason it comes out as 0.0
                    //  meaning the drawing comes out transparent.
                    newFormatedBitmapSource = new FormatConvertedBitmap();
                    newFormatedBitmapSource.BeginInit();
                    newFormatedBitmapSource.Source            = BitmapConversion.HBitmapToBitmapSource(provider.DIBSection.HBitmap);
                    newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24;
                    newFormatedBitmapSource.EndInit();
                    break;
                }

                case RenderContextType.NativeWindow:
                    break;

                case RenderContextType.HiddenWindow:
                    break;

                case RenderContextType.FBO:
                {
                    FBORenderContextProvider provider = Gl.RenderContextProvider as FBORenderContextProvider;
                    //hBitmap = provider.InternalDIBSection.HBitmap;
                    //break;
                    //  TODO: We have to remove the alpha channel - for some reason it comes out as 0.0
                    //  meaning the drawing comes out transparent.
                    newFormatedBitmapSource = new FormatConvertedBitmap();
                    newFormatedBitmapSource.BeginInit();
                    newFormatedBitmapSource.Source            = BitmapConversion.HBitmapToBitmapSource(provider.InternalDIBSection.HBitmap);
                    newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24;
                    newFormatedBitmapSource.EndInit();
                    break;
                }
                }

                //Bitmap res = hBitmap != null ? Bitmap.FromHbitmap(hBitmap) : null;
                //return res;

                return(newFormatedBitmapSource);
            }
        }
        /// <summary>
        /// This method converts the output from the OpenGL render context provider to a
        /// FormatConvertedBitmap in order to show it in the image.
        /// </summary>
        /// <param name="handle">The handle of the bitmap from the OpenGL render context.</param>
        /// <returns>Returns the new format converted bitmap.</returns>
        private static FormatConvertedBitmap GetFormatedBitmapSource(IntPtr handle)
        {
            // TODO: We have to remove the alpha channel - for some reason it comes out as 0.0
            // meaning the drawing comes out transparent
            FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();

            newFormatedBitmapSource.BeginInit();
            newFormatedBitmapSource.Source            = BitmapConversion.HBitmapToBitmapSource(handle);
            newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24;
            newFormatedBitmapSource.EndInit();

            return(newFormatedBitmapSource);
        }
 public SectionReadWindow(Section section, bool showing)
 {
     InitializeComponent();
     Points              = new List <Point>();
     Markers             = new List <Point>();
     SectionName.Text    = section.Name;
     SectionImage.Source = BitmapConversion.ToWpfBitmap(section.Image);
     IsOnlyShowing       = showing;
     if (showing)
     {
         CommandBlock.Visibility = Visibility.Hidden;
     }
 }
Example #12
0
        private void UpdateImageSource(IntPtr hBitmap)
        {
            //  TODO: We have to remove the alpha channel - for some reason it comes out as 0.0
            //  meaning the drawing comes out transparent.
            var newFormatedBitmapSource = new FormatConvertedBitmap();

            newFormatedBitmapSource.BeginInit();
            newFormatedBitmapSource.Source            = BitmapConversion.HBitmapToBitmapSource(hBitmap);
            newFormatedBitmapSource.DestinationFormat = PixelFormats.Rgb24;
            newFormatedBitmapSource.EndInit();

            //  Copy the pixels over.
            OnImageSourceUpdated(new ImageSourceEventArg(newFormatedBitmapSource));
        }
Example #13
0
        public void LoadImage()
        {
            ChaoDataBase  cdb  = new ChaoDataBase();
            List <byte[]> list = new List <byte[]>();

            list      = cdb.SelectImage("bigpic");
            ImageList = new List <BitmapSource>();
            cdb.CloseDB();
            BitmapImage = new MemoryStream(list[0]);
            list.ForEach(arg => {
                ImageList.Add(BitmapConversion.BitmapToBitmapSource((byteArrayToImage(arg))));
                //ImageList.Add(loadBitmap(byteArrayToImage(arg)));
                //ImageList.Add(new MemoryStream(arg));
            });
        }
Example #14
0
        private void OnDrop(object args)
        {
            if (args is DragEventArgs dragEventArgs)
            {
                string[] data = (string[])dragEventArgs.Data.GetData(DataFormats.FileDrop);

                for (int i = 0; i < data.Length; i++)
                {
                    if (Helper.SuitableExtention(data[i]))
                    {
                        Images.Add(new Image(data[i], BitmapConversion.ImagePathToBitmapSource(data[i])));
                    }
                }
            }
        }
Example #15
0
    // Start is called before the first frame update
    void Start()
    {
        //TestImages t = new TestImages("lena");

        Bitmap image = BitmapConversion.Texture2DToBitmap(inputTex);

        FastCornersDetector fast = new FastCornersDetector(20);



        // Create a new AForge's Corner Marker Filter
        CornersMarker corners = new CornersMarker(fast, System.Drawing.Color.White);

        corners.ApplyInPlace(image);
        // Apply the filter and display it on a picturebox
        rawImage.texture = BitmapConversion.BitmapToTexture2D(image);
    }
Example #16
0
        /// <summary>
        /// Fill the ImageSource from the provided bits IntPtr, using the provided hBitMap IntPtr
        /// if needed to determine key data from the bitmap source.
        /// </summary>
        /// <param name="bits">An IntPtr to the bits for the bitmap image.  Generally provided from
        /// DIBSectionRenderContextProvider.DIBSection.Bits or from
        /// FBORenderContextProvider.InternalDIBSection.Bits.</param>
        /// <param name="hBitmap">An IntPtr to the HBitmap for the image.  Generally provided from
        /// DIBSectionRenderContextProvider.DIBSection.HBitmap or from
        /// FBORenderContextProvider.InternalDIBSection.HBitmap.</param>
        public void FillImageSource(IntPtr bits, IntPtr hBitmap)
        {
            // If DPI hasn't been set, use a call to HBitmapToBitmapSource to fill the info
            // This should happen only ONCE (near the start of the application)
            if (_dpiX == 0)
            {
                var bitmapSource = BitmapConversion.HBitmapToBitmapSource(hBitmap);
                _dpiX          = bitmapSource.DpiX;
                _dpiY          = bitmapSource.DpiY;
                _format        = bitmapSource.Format;
                _bytesPerPixel = gl.RenderContextProvider.BitDepth >> 3;
                // FBO render context flips the image vertically, so transform to compensate
                if (RenderContextType == RenderContextType.FBO)
                {
                    image.RenderTransform       = new ScaleTransform(1.0, -1.0);
                    image.RenderTransformOrigin = new Point(0.0, 0.5);
                }
                else
                {
                    image.RenderTransform       = Transform.Identity;
                    image.RenderTransformOrigin = new Point(0.0, 0.0);
                }
            }
            // If the image buffer is null, create it
            // This should happen when the size of the image changes
            if (_imageBuffer == null)
            {
                int width  = gl.RenderContextProvider.Width;
                int height = gl.RenderContextProvider.Height;

                int imageBufferSize = width * height * _bytesPerPixel;
                _imageBuffer     = new byte[imageBufferSize];
                _writeableBitmap = new WriteableBitmap(width, height, _dpiX, _dpiY, _format, null);
                _imageRect       = new Int32Rect(0, 0, width, height);
                _imageStride     = width * _bytesPerPixel;
            }

            // Fill the image buffer from the bits and update the writeable bitmap
            System.Runtime.InteropServices.Marshal.Copy(bits, _imageBuffer, 0, _imageBuffer.Length);
            // FIXME Remove transparency
            // for (int i = 3; i < _imageBuffer.Length; i+=4) _imageBuffer[i] = 255;
            _writeableBitmap.WritePixels(_imageRect, _imageBuffer, _imageStride, 0);

            image.Source = _writeableBitmap;
        }
        private async void SaveHandler()
        {
            try
            {
                var             id   = Global.LoggedUser.ID;
                RepositoryModel item = null;
                await Task.Run(() =>
                {
                    using (CoreContext context = new CoreContext())
                    {
                        Repository repo = new DataLayer.Models.Repository()
                        {
                            SampleImage = Repository.SampleImage,
                            UserID      = Repository.UserID
                        };
                        var user = context.Users.FirstOrDefault(x => x.ID == id);
                        if (user != null)
                        {
                            user.Repositories.Add(repo);
                            context.SaveChanges();
                            BitmapImage image = BitmapReader.Read(Repository.SampleImage);
                            Bitmap bitmap     = BitmapConversion.BitmapImageToBitmap(image);
                            item = new RepositoryModel
                            {
                                ID          = repo.ID,
                                UserID      = repo.UserID,
                                SampleImage = repo.SampleImage,
                                Image       = BitmapConversion.BitmapToBitmapSource(bitmap),
                            };
                        }
                    }
                });

                if (item != null)
                {
                    Repositories.Add(item);
                    Repository = null;
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogException(new string[] { ex.ToString() });
            }
        }
        private void Execute()
        {
            async Task InitializeLP() //initialize methods that use Get/Set Pixel
            {
                MeasureTime measureLP = new MeasureTime();

                Bitmaps.BinarizeLPImage     = BitmapConversion.CreateNonIndexedImage(new Bitmap(Bitmaps.Filepath));
                Bitmaps.BinarizeLPImageView = await Task.Run(() => Binarization.LowPerformance(new Bitmap(Bitmaps.Filepath), Bitmaps.BinarizeLPImage, measureLP));

                Bitmaps.KMMLP = await Task.Run(() => KMMLowPerformanceMain.Init(Bitmaps.BinarizeLPImage, measureLP));

                Bitmaps.TimeElapsedLP = measureLP.TimeElapsedMs;
            }

            async Task InitializeHP() //initialize methods with lockbits, marshall copy
            {
                MeasureTime measureHP = new MeasureTime();

                Bitmaps.BinarizeHPImage = await Task.Run(() => Binarization.HighPerformance(new Bitmap(Bitmaps.Filepath), measureHP));

                Bitmaps.BinarizeHPImageView = BitmapConversion.Bitmap2BitmapImage(Bitmaps.BinarizeHPImage);
                Bitmaps.KMMHP = await Task.Run(() => BitmapConversion.Bitmap2BitmapImage(KMMHighPerformanceMain.Init(Bitmaps.BinarizeHPImage, measureHP)));

                Bitmaps.TimeElapsedHP      = measureHP.TimeElapsedMs;
                Bitmaps.TimeElapsedHPTicks = measureHP.TimeElapsedTicks;
            }

            try
            {
                var task1 = Task.Run(() => InitializeLP());
                var task2 = Task.Run(() => InitializeHP());
                Task.WaitAll(task1, task2);
            }

            catch (Exception ex)
            {
                if (ex is ArgumentNullException || ex is AggregateException)
                {
                    System.Windows.MessageBox.Show("There is no image to Apply KMM");
                }
            }
        }
Example #19
0
        //-------------------------------------------------------------------
        // SetConversionFunction
        //
        // Set the conversion function for the specified video format.
        //-------------------------------------------------------------------

        private HResult SetConversionFunction(Guid subtype)
        {
            HResult hr = HResult.MF_E_INVALIDMEDIATYPE;

            m_convertFn    = null;
            m_bmpconvertFn = null;

            for (int i = 0; i < VideoFormatDefs.Length; i++)
            {
                if (VideoFormatDefs[i].SubType == subtype)
                {
                    m_convertFn    = VideoFormatDefs[i].VideoConvertFunction;
                    m_bmpconvertFn = VideoFormatDefs[i].BitmapConvertFunction;
                    hr             = HResult.S_OK;
                    break;
                }
            }

            return(hr);
        }
        public static unsafe Bitmap Init(Bitmap resultBmp, MeasureTime measure)
        {
            var stopwatch = Stopwatch.StartNew();

            resultBmp = BitmapConversion.Create8bppGreyscaleImage(resultBmp);
            BitmapData bmpData = resultBmp.LockBits(new Rectangle(0, 0, resultBmp.Width, resultBmp.Height),
                                                    ImageLockMode.ReadWrite,
                                                    resultBmp.PixelFormat
                                                    );

            int bytes = bmpData.Stride * resultBmp.Height;

            byte[] pixels = new byte[bytes];

            Marshal.Copy(bmpData.Scan0, pixels, 0, bytes);
            int height = resultBmp.Height;
            int width  = resultBmp.Width;

            int deletion = 1;
            int deletionFirst, deletionSecond;

            while (deletion != 0)
            {
                deletion = 0;

                pixels = HighPerformance.SetOneTwoThree(pixels, bmpData.Stride, height, width);
                (deletionFirst, pixels)  = HighPerformance.FindAndDeleteFour(pixels, bmpData.Stride, height, width, deletion);
                (deletionSecond, pixels) = HighPerformance.DeletingTwoThree(pixels, bmpData.Stride, height, width, deletion);

                deletion = deletionFirst > deletionSecond ? deletionFirst : deletionSecond;
            }

            Marshal.Copy(pixels, 0, bmpData.Scan0, bytes);
            resultBmp.UnlockBits(bmpData);

            stopwatch.Stop();
            measure.SumTimeElapsedMs(stopwatch.ElapsedMilliseconds);
            measure.SumTimeElapsedTicks(stopwatch.ElapsedTicks);
            return(resultBmp);
        }
        public static void SaveImageToFile(BitmapImage image)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog()
            {
                Filter = "PNG Image|*.png",
            };

            if (saveFileDialog.ShowDialog() == true && saveFileDialog.FileName != String.Empty)
            {
                try
                {
                    Bitmap bmp = BitmapConversion.BitmapImage2Bitmap(image);
                    //Image toSave = bmp;
                    bmp.Save("dupa.png", ImageFormat.Png);
                }

                catch (ArgumentNullException ex)
                {
                    MessageBox.Show("There is no final image to save");
                }
            }
        }
Example #22
0
        public static ObservableCollection <Image> GetImagesFromFolder()
        {
            var result = new ObservableCollection <Image>();

            string photoDir = Directory.GetCurrentDirectory() + @"\Photos";

            if (Directory.Exists(photoDir))
            {
                var folderFiles = Directory.GetFiles(photoDir);

                for (int i = 0; i < folderFiles.Length; i++)
                {
                    string extension = Path.GetExtension(folderFiles[i]).ToLower();
                    if (Helper.SuitableExtention(folderFiles[i]))
                    {
                        result.Add(new Image(folderFiles[i], BitmapConversion.ImagePathToBitmapSource(folderFiles[i])));
                    }
                }
            }

            return(result);
        }
        public async void LoadSamples()
        {
            try
            {
                var id = Global.LoggedUser.ID;
                List <RepositoryModel> list = new List <RepositoryModel>();
                await Task.Run(() =>
                {
                    using (CoreContext context = new CoreContext())
                    {
                        var result = context.Repositories.Where(x => x.UserID == id).ToList();
                        if (result != null && result.Count > 0)
                        {
                            foreach (var item in result)
                            {
                                RepositoryModel model = new RepositoryModel
                                {
                                    ID          = item.ID,
                                    UserID      = item.UserID,
                                    SampleImage = item.SampleImage
                                };

                                BitmapImage image = BitmapReader.Read(item.SampleImage);
                                Bitmap bitmap     = BitmapConversion.BitmapImageToBitmap(image);
                                model.Image       = BitmapConversion.BitmapToBitmapSource(bitmap);

                                list.Add(model);
                            }
                            Repositories = new ObservableCollection <RepositoryModel>(list);
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                LogHelper.LogException(new string[] { ex.ToString() });
            }
        }
Example #24
0
 public VideoFormatGUID(Guid FormatGuid, VideoConversion cvt, BitmapConversion bmpcvt)
 {
     SubType = FormatGuid;
     VideoConvertFunction = cvt;
     BitmapConvertFunction = bmpcvt;
 }
Example #25
0
        private void onExportedObjectSelected(ExportedObjectSelectedMessage message)
        {
            string extension = Path.GetExtension(message.Filename)?.ToLowerInvariant();

            switch (extension)
            {
            case ".ogg":
            {
                Task.Run(() => playSound(new FileStream(message.Filename, FileMode.Open), resetToken())).FireAndForget();

                break;
            }

            case ".dds":
            {
                DdsFile image = new DdsFile(message.Filename);

                viewModel.MipMaps = null;

                viewModel.Texture = image.BitmapSource;

                break;
            }

            case ".ttf":
            case ".otf":
            {
                using (MemoryStream fontms = new MemoryStream(File.ReadAllBytes(message.Filename)))
                {
                    var fontfamilies = FontConversion.Load(fontms);
                    var fontfamily   = fontfamilies.Families.First();

                    using (Bitmap b = new Bitmap(600, 400))
                    {
                        using (Graphics g = Graphics.FromImage(b))
                        {
                            g.Clear(Color.White);         // White background
                            using (Font font = new Font(fontfamily, 24, FontStyle.Regular, GraphicsUnit.Pixel))
                            {
                                using (Font arial = new Font(new FontFamily("Arial"), 24, FontStyle.Regular, GraphicsUnit.Pixel))
                                {
                                    using (SolidBrush solidBrush = new SolidBrush(Color.Black))
                                    {
                                        g.DrawString(String.Format("{0}, {1}, {2}px", font.Name, font.Style, 24), arial, solidBrush, new RectangleF(10, 10, 600, 600));
                                    }
                                }
                                using (SolidBrush solidBrush = new SolidBrush(Color.Black))
                                {
                                    g.DrawString("abcdefghijklmnopqrstuvwxyz", font, solidBrush, new RectangleF(10, 36, 600, 600));
                                    g.DrawString("ABCDEFGHIJKLMNOPQRSTUVWXYZ", font, solidBrush, new RectangleF(10, 62, 600, 600));
                                    g.DrawString("1234567890", font, solidBrush, new RectangleF(10, 88, 600, 600));
                                    g.DrawString("The quick brown fox jumps over the lazy dog.", font, solidBrush, new RectangleF(10, 114, 600, 600));
                                }
                            }
                            using (Font font = new Font(fontfamily, 48, FontStyle.Regular, GraphicsUnit.Pixel))
                            {
                                using (SolidBrush solidBrush = new SolidBrush(Color.Black))
                                {
                                    g.DrawString("The quick brown fox jumps over the lazy dog.", font, solidBrush, new RectangleF(10, 166, 600, 600));
                                }
                            }
                        }
                        viewModel.Texture = BitmapConversion.ToWpfBitmap(b);
                    }
                }
                break;
            }
            }
        }
Example #26
0
        private void onExportObjectSelected(ExportTableEntrySelectedMessage message)
        {
            if (message.ExportTableEntry.DomainObject == null)
            {
                return;
            }

            switch (message.ExportTableEntry.DomainObject.Viewable)
            {
            case ViewableTypes.Sound:
            {
                Task.Run(() => playSound(message.ExportTableEntry.DomainObject.GetObjectStream(), resetToken())).FireAndForget();

                break;
            }

            case ViewableTypes.Image:
            {
                texture = message.ExportTableEntry.DomainObject as DomainObjectTexture2D;

                if (texture != null)
                {
                    clearViewModel();

                    viewModel.MipMaps = new ObservableCollection <MipMapViewEntity>(mapper.Map <IEnumerable <MipMapViewEntity> >(texture.MipMaps));

                    for (int i = 0; i < viewModel.MipMaps.Count; ++i)
                    {
                        viewModel.MipMaps[i].Level = i + 1;

                        viewModel.MipMaps[i].PropertyChanged += onMipMapViewEntityChanged;
                    }

                    MipMapViewEntity largest = viewModel.MipMaps.Aggregate((i1, i2) => i1 != null && i1.IsEnabled & (i1.Width > i2.Width || i1.Height > i2.Height) ? i1 : (i2.IsEnabled ? i2 : null));

                    if (largest != null)
                    {
                        largest.IsChecked = true;
                    }
                }

                break;
            }

            case ViewableTypes.Font:
            {
                var fontexport = message.ExportTableEntry.DomainObject as DomainObjectFontResource;
                using (MemoryStream fontms = new MemoryStream(fontexport.Font))
                {
                    var fontfamilies = FontConversion.Load(fontms);
                    var fontfamily   = fontfamilies.Families.First();

                    using (Bitmap b = new Bitmap(600, 400))
                    {
                        using (Graphics g = Graphics.FromImage(b))
                        {
                            g.Clear(Color.White);         // White background
                            using (Font font = new Font(fontfamily, 24, FontStyle.Regular, GraphicsUnit.Pixel))
                            {
                                using (Font arial = new Font(new FontFamily("Arial"), 24, FontStyle.Regular, GraphicsUnit.Pixel))
                                {
                                    using (SolidBrush solidBrush = new SolidBrush(Color.Black))
                                    {
                                        g.DrawString(String.Format("{0}, {1}, {2}px", font.Name, font.Style, 24), arial, solidBrush, new RectangleF(10, 10, 600, 600));
                                    }
                                }
                                using (SolidBrush solidBrush = new SolidBrush(Color.Black))
                                {
                                    g.DrawString("abcdefghijklmnopqrstuvwxyz", font, solidBrush, new RectangleF(10, 36, 600, 600));
                                    g.DrawString("ABCDEFGHIJKLMNOPQRSTUVWXYZ", font, solidBrush, new RectangleF(10, 62, 600, 600));
                                    g.DrawString("1234567890", font, solidBrush, new RectangleF(10, 88, 600, 600));
                                    g.DrawString("The quick brown fox jumps over the lazy dog.", font, solidBrush, new RectangleF(10, 114, 600, 600));
                                }
                            }
                            using (Font font = new Font(fontfamily, 48, FontStyle.Regular, GraphicsUnit.Pixel))
                            {
                                using (SolidBrush solidBrush = new SolidBrush(Color.Black))
                                {
                                    g.DrawString("The quick brown fox jumps over the lazy dog.", font, solidBrush, new RectangleF(10, 166, 600, 600));
                                }
                            }
                        }
                        viewModel.Texture = BitmapConversion.ToWpfBitmap(b);
                    }
                }
                break;
            }

            default:
            {
                clearViewModel();

                break;
            }
            }
        }
 public override object ProvideValue(IServiceProvider serviceProvider)
 {
     return(BitmapConversion.BitmapToBitmapSource((Bitmap)Bitmap.FromFile(Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + path + ImageName + ".png", true)));
 }
Example #28
0
        //-------------------------------------------------------------------
        // SetVideoType
        //
        // Set the video format.
        //-------------------------------------------------------------------
        public HResult SetVideoType(IMFMediaType pType)
        {
            HResult hr = HResult.S_OK;
            Guid    subtype;
            MFRatio PAR = new MFRatio();

            // Find the video subtype.
            hr = pType.GetGUID(MFAttributesClsid.MF_MT_SUBTYPE, out subtype);
            if (Failed(hr))
            {
                goto done;
            }

            // Choose a conversion function.
            // (This also validates the format type.)

            hr = SetConversionFunction(subtype);
            if (Failed(hr))
            {
                goto done;
            }

            //
            // Get some video attributes.
            //

            // Get the frame size.
            hr = MFExtern.MFGetAttributeSize(pType, MFAttributesClsid.MF_MT_FRAME_SIZE, out m_width, out m_height);
            if (Failed(hr))
            {
                goto done;
            }

            // Get the image stride.
            hr = GetDefaultStride(pType, out m_lDefaultStride);
            if (Failed(hr))
            {
                goto done;
            }

            // Get the pixel aspect ratio. Default: Assume square pixels (1:1)
            hr = MFExtern.MFGetAttributeRatio(pType, MFAttributesClsid.MF_MT_PIXEL_ASPECT_RATIO, out PAR.Numerator, out PAR.Denominator);

            if (Succeeded(hr))
            {
                m_PixelAR = PAR;
            }
            else
            {
                m_PixelAR.Numerator = m_PixelAR.Denominator = 1;
            }

            FourCC f = new FourCC(subtype);

            m_format = (Format)f.ToInt32();

            // Create Direct3D swap chains.

            hr = CreateSwapChains();
            if (Failed(hr))
            {
                goto done;
            }

            // Update the destination rectangle for the correct
            // aspect ratio.

            UpdateDestinationRect();

done:
            if (Failed(hr))
            {
                m_format       = Format.Unknown;
                m_convertFn    = null;
                m_bmpconvertFn = null;
            }

            return(hr);
        }
Example #29
0
 public VideoFormatGUID(Guid FormatGuid, VideoConversion cvt, BitmapConversion bmpcvt)
 {
     SubType = FormatGuid;
     VideoConvertFunction  = cvt;
     BitmapConvertFunction = bmpcvt;
 }
Example #30
0
        //-------------------------------------------------------------------
        // SetConversionFunction
        //
        // Set the conversion function for the specified video format.
        //-------------------------------------------------------------------
        private int SetConversionFunction(Guid subtype)
        {
            int hr = MFError.MF_E_INVALIDMEDIATYPE;
            m_convertFn = null;
            m_bmpconvertFn = null;

            for (int i = 0; i < VideoFormatDefs.Length; i++)
            {
                if (VideoFormatDefs[i].SubType == subtype)
                {
                    m_convertFn = VideoFormatDefs[i].VideoConvertFunction;
                    m_bmpconvertFn = VideoFormatDefs[i].BitmapConvertFunction;
                    hr = S_Ok;
                    break;
                }
            }

            return hr;
        }
Example #31
0
        //-------------------------------------------------------------------
        // SetVideoType
        //
        // Set the video format.
        //-------------------------------------------------------------------
        public int SetVideoType(IMFMediaType pType)
        {
            int hr = S_Ok;
            Guid subtype;
            MFRatio PAR = new MFRatio();

            // Find the video subtype.
            hr = pType.GetGUID(MFAttributesClsid.MF_MT_SUBTYPE, out subtype);
            if (Failed(hr)) { goto done; }

            // Choose a conversion function.
            // (This also validates the format type.)

            hr = SetConversionFunction(subtype);
            if (Failed(hr)) { goto done; }

            //
            // Get some video attributes.
            //

            // Get the frame size.
            hr = MFGetAttributeSize(pType, MFAttributesClsid.MF_MT_FRAME_SIZE, out m_width, out m_height);
            if (Failed(hr)) { goto done; }

            // Get the image stride.
            hr = GetDefaultStride(pType, out m_lDefaultStride);
            if (Failed(hr)) { goto done; }

            // Get the pixel aspect ratio. Default: Assume square pixels (1:1)
            hr = MFGetAttributeRatio(pType, MFAttributesClsid.MF_MT_PIXEL_ASPECT_RATIO, out PAR.Numerator, out PAR.Denominator);

            if (Succeeded(hr))
            {
                m_PixelAR = PAR;
            }
            else
            {
                m_PixelAR.Numerator = m_PixelAR.Denominator = 1;
            }

            FourCC f = new FourCC(subtype);
            m_format = (Format)f.ToInt32();

            // Create Direct3D swap chains.

            hr = CreateSwapChains();
            if (Failed(hr)) { goto done; }

            // Update the destination rectangle for the correct
            // aspect ratio.

            UpdateDestinationRect();

            done:
            if (Failed(hr))
            {
                m_format = Format.Unknown;
                m_convertFn = null;
                m_bmpconvertFn = null;
            }

            return hr;
        }
Example #32
0
        //-------------------------------------------------------------------
        // Constructor
        //-------------------------------------------------------------------
        public DrawDevice()
        {
            m_hwnd = IntPtr.Zero;
            m_pDevice = null;
            m_pSwapChain = null;

            m_d3dpp = null;
            m_Data = IntPtr.Zero;

            m_format = Format.X8R8G8B8;
            m_width = 0;
            m_height = 0;
            m_lDefaultStride = 0;
            m_PixelAR.Denominator = m_PixelAR.Numerator = 1;
            m_rcDest = Rectangle.Empty;

            VideoFormatDefs = new VideoFormatGUID[] {
                new VideoFormatGUID(MFMediaType.RGB32, TransformImage_RGB32, ARGB32_To_RGB32),
                new VideoFormatGUID(MFMediaType.RGB24, TransformImage_RGB24, ARGB32_To_RGB24),
                new VideoFormatGUID(MFMediaType.YUY2, TransformImage_YUY2, ARGB32_To_YUY2),
                new VideoFormatGUID(MFMediaType.NV12, TransformImage_NV12, ARGB32_To_NV12)
            };

            m_convertFn = null;
            m_bmpconvertFn = null;
        }