Hang .001

1, issue:

 (20,190,821) when doing video image analysis, the release version of the exe encountered in BitmapSourceConvert.ToBitmapSource (IImage image) function error, but also a direct memory error catch exception handler Application_DispatcherUnhandledException grasp the overall situation (...) can be caught less than direct ... exe crashes ...

  The specific function of the position error is: "IntPtr ptr = source.GetHbitmap ();" ZC: here to get a handle bitmap why will complain, do not understand ... Is it bitmap is empty inside? Invalid? Will take the lead to handle the wrong time?

2, I try to do:

 2.1, personal feeling is that the memory is released prematurely GC? ? Then stepped on the memory should not be stepped on? ? So try System.Drawing.Bitmap.LockBits (...) lock memory, my thoughts always locked memory that can be used, right? But LockBits () after exe still crash ...

 2.2, find another way to turn BitmapSource Bitmap, which is the direct access memory (not through the handle, ∴ do not need to get a handle), which shows the inside of the Bitmap memory is OK, just the wrong time to take a handle (∴ LockBits not work) ...

  (1) in the end I want to know why Bitmap.GetHbitmap () will go wrong: we do not know how to get, they did not know how to look Bitmap.GetHbitmap () inside the source / assembler, online search do not have this problem ... in abeyance. ..

3, Code:

class BitmapSourceConvert
    {
        /// <summary>
        /// Delete a GDI object
        /// </summary>
        /// <param name="o">The poniter to the GDI object to be deleted</param>
        /// <returns></returns>
        [DllImport("gdi32")]
        private static extern int DeleteObject(IntPtr o);

        /// <summary>
        /// Convert an IImage to a WPF BitmapSource. The result can be used in the Set Property of Image.Source
        /// </summary>
        /// <param name="image">The Emgu CV Image</param>
        /// <returns>The equivalent BitmapSource</returns>
        public static BitmapSource ToBitmapSource(IImage image)
        {
            try
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();
                //System.Drawing.Bitmap source = image.Bitmap;
                using (System.Drawing.Bitmap source = image.Bitmap)
                {
                    Console.WriteLine("ToBitmapSource(...) - 1");
                    BitmapData bd = source.LockBits(
                        new Rectangle(0, 0, source.Width, source.Height),
                        System.Drawing.Imaging.ImageLockMode.ReadWrite, source.PixelFormat);
                    unsafe
                    {
                        int* pii = (int*)bd.Scan0;
                        Console.WriteLine("ToBitmapSource(...) - 1.1 : {0}", pii[0]);
                    }

                    //IntPtr pp = image.Ptr;
                    //unsafe
                    //{
                    //    BitmapData bitmapData = source.LockBits(
                    //        new Rectangle(0, 0, source.Width, source.Height),
                    //        System.Drawing.Imaging.ImageLockMode.ReadWrite, source.PixelFormat);
                    //    int* pii = (int*)bitmapData.Scan0;
                    //    Console.WriteLine("ToBitmapSource(...) - 1 : {0} : {1}, {2}, {3}",
                    //        bitmapData.PixelFormat, pii[0], pii[10], pii[20]);

                    //        //PixelFormat.Format24bppRgb

                    //    int* pi = (int*)pp;
                    //    Console.WriteLine("ToBitmapSource(...) - 2 : {0}; {1}, {2}:{3}, {4}, {5}",
                    //        source, source.Size, image.Ptr, pi[0], pi[10], pi[20]);
                    //}

                    Console.WriteLine("ToBitmapSource(...) - 2");
                    IntPtr ptr = source.GetHbitmap(); //obtain the Hbitmap
                    
                    Console.WriteLine("ToBitmapSource(...) - 3");

                    BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                        ptr,
                        IntPtr.Zero,
                        Int32Rect.Empty,
                        System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());

                    sw.Stop();
                    Console.WriteLine("ToBitmapSource(...) ElapsedMilliseconds : {0}", sw.ElapsedMilliseconds);
                    //source.UnlockBits(bd);
                    DeleteObject(ptr); //release the HBitmap
                    return bs;
                }
            }
            catch (Exception _ex)
            {
                string str = "ToBitmapSource(...) err : " + _ex.Message+", ["+DateTime.Now+"]";
                Console.WriteLine(str);
                Trace.TraceError(str);

                return null;
            }
        }

        //public static BitmapSource ToBitmapSource(Mat _mat)
        //{
        //    //try
        //    //{
        //    _mat.to.Bitmap
        //    Bitmap source = Image.FromStream(new MemoryStream(_mat.Data));
        //    Bitmap source = new Bitmap(_mat.Width, _mat.Height);
        //    source
        //    Bitmap ^ test = gcnew Bitmap(matToConvert.rows, matToConvert.cols, 4 * matToConvert.rows, System::Drawing::Imaging::PixelFormat::Format4bppIndexed, IntPtr(matToConvert.data));

        //    Console.WriteLine("_mat.NumberOfChannels : {0}", _mat.NumberOfChannels);
        //    BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromMemorySection(
        //        _mat.Ptr, _mat.Width, _mat.Height, PixelFormats.Bgr24, (int)(_mat.Width * PixelFormats.Bgr24.BitsPerPixel / 8), 0);
        //    return bs;
        //    //}
        //    // the catch (Exception _ex)
         //     // {
         //     //     String STR = "ToBitmapSource (Mat) ERR:" + _ex.Message + ", [" the DateTime.Now + + "]";
         //     //     Console .WriteLine (STR);
         //     //     Trace.TraceError (STR); 

        //     //     return null;
         //     // }
         // }

// the ZC: where the transfer function is derived from: "Bitmap converted to BitmapSource - koloumi the blog - CSDN blog .html ( https://blog.csdn.net/koloumi/article/details/80577249 ) "
// ZC: which fly in the ointment: more than a MemoryStream, you need to copy the memory. public static BitmapSource ToBitmapSource (Mat _mat) { System.Windows.Media.Imaging.BitmapFrame bf = null; //Stopwatch sw = new Stopwatch(); //sw.Start(); using (System.Drawing.Bitmap bmp = _mat.Bitmap) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { //Console.WriteLine("zzzzz(...) - 1"); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); //Console.WriteLine("zzzzz(...) - 2"); bf = System.Windows.Media.Imaging.BitmapFrame.Create(ms, System.Windows.Media.Imaging.BitmapCreateOptions.None, System.Windows.Media.Imaging.BitmapCacheOption.OnLoad); //sw.Stop(); //Console.WriteLine("zzzzz(...) ElapsedMilliseconds : {0}", sw.ElapsedMilliseconds); //Console.WriteLine("zzzzz(...) - 3"); } } return bf; } }

 

4、

5、

 

Guess you like

Origin www.cnblogs.com/csskill/p/11387092.html
001