How to convert ImageSource to Bitmap for cross-platform project(xamarin)

本小妞迷上赌 提交于 2019-12-25 02:56:29

问题


I found an example, but this example use a "Int32Rect", class of System.Windows, we can't use this library for android or ios

For bitmap, i use the System.Drawing.Common

public static System.Drawing.Bitmap BitmapSourceToBitmap2(BitmapSource srs)
        {
            int width = srs.PixelWidth;
            int height = srs.PixelHeight;
            int stride = width * ((srs.Format.BitsPerPixel + 7) / 8);
            IntPtr ptr = IntPtr.Zero;
            try
            {
                ptr = Marshal.AllocHGlobal(height * stride);
                srs.CopyPixels(new Int32Rect(0, 0, width, height), ptr, height * stride, stride);
                using (var btm = new System.Drawing.Bitmap(width, height, stride, System.Drawing.Imaging.PixelFormat.Format1bppIndexed, ptr))
                {
                    // Clone the bitmap so that we can dispose it and
                    // release the unmanaged memory at ptr
                    return new System.Drawing.Bitmap(btm);
                }
            }
            finally
            {
                if (ptr != IntPtr.Zero)
                    Marshal.FreeHGlobal(ptr);
            }
        }

So, how to convert ImageSource to Bitmap for cross-platform project?

I tried to follow guide, there was incomplete information in it and I tried to fill in the understatement on my own

The project even compiles! However, when I try to get the result from the GetBitmapFromImageSourceAsync (…) method, the application freezes (infinite loop)

var test = GetBitmapFromImageSourceAsync(image, Android.App.Application.Context);
var bitmap = test.Result;

Please see why it does not work? Or please give me a link to your project and I’ll figure it out

https://github.com/StriBog45/XamarinImage

来源:https://stackoverflow.com/questions/54764681/how-to-convert-imagesource-to-bitmap-for-cross-platform-projectxamarin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!