C# 从位图设置图像

C# 从位图设置图像,c#,android,xamarin,xamarin.forms,C#,Android,Xamarin,Xamarin.forms,Android.Widget.ImageView包含方法SetImageBitmap 从我的位图设置Xamarin.Forms.Image的最佳方法是什么?通过 提到了两种解决方案 为了创建一个图像,我尝试了@Wosi的答案,但由于某种原因,之后的图像渲染不起作用,代码是针对Android的。我需要从字节数组转换成位图,然后再转换回来。这就是我所做的: 将位图转换为字节数组的代码: var image = new Image(); image.Source = ImageSource.From

Android.Widget.ImageView包含方法SetImageBitmap

从我的位图设置Xamarin.Forms.Image的最佳方法是什么?

通过

提到了两种解决方案


  • 为了创建一个
    图像

    ,我尝试了@Wosi的答案,但由于某种原因,之后的图像渲染不起作用,代码是针对Android的。我需要从字节数组转换成位图,然后再转换回来。这就是我所做的:

    将位图转换为字节数组的代码:

    var image = new Image();
    image.Source = ImageSource.FromStream(() => new MemoryStream(byteArray));
    
    以及将字节数组转换为位图的代码:

            byte[] bitmapData;
            using (var stream = new MemoryStream())
            {
                tempBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 0, stream);
                bitmapData = stream.ToArray();
            }
    
    其中“选项”的定义如下:

     Android.Graphics.Bitmap tempBitmap = Android.Graphics.BitmapFactory.DecodeByteArray(imageByteArray, 0, imageByteArray.Length, options);
    
            Android.Graphics.BitmapFactory.Options options = new Android.Graphics.BitmapFactory.Options
            {
                InJustDecodeBounds = true
            };
            Android.Graphics.Bitmap result = Android.Graphics.BitmapFactory.DecodeByteArray(bitmapArray, 0, byteArrayLength, options);
            //int imageHeight = options.OutHeight;
            //int imageWidth = options.OutWidth;
    
    在这一部分中,位图被解码。这样做是为了获得图像的高度和宽度属性。在我的例子中,我需要这些信息来再次将其编码为字节数组

    这样就可以将字节数组编码为字符串,然后再编码回来

    从字节数组设置图像源的操作如下:

     Android.Graphics.Bitmap tempBitmap = Android.Graphics.BitmapFactory.DecodeByteArray(imageByteArray, 0, imageByteArray.Length, options);
    
            Android.Graphics.BitmapFactory.Options options = new Android.Graphics.BitmapFactory.Options
            {
                InJustDecodeBounds = true
            };
            Android.Graphics.Bitmap result = Android.Graphics.BitmapFactory.DecodeByteArray(bitmapArray, 0, byteArrayLength, options);
            //int imageHeight = options.OutHeight;
            //int imageWidth = options.OutWidth;
    

    @基里尔河本身不会经过。传递一个创建流的方法。请参阅答案中最后一行代码的更改。第一个解决方案有异常,第二个解决方案-image.Width==-1(也不起作用)
            Android.Graphics.BitmapFactory.Options options = new Android.Graphics.BitmapFactory.Options
            {
                InJustDecodeBounds = true
            };
            Android.Graphics.Bitmap result = Android.Graphics.BitmapFactory.DecodeByteArray(bitmapArray, 0, byteArrayLength, options);
            //int imageHeight = options.OutHeight;
            //int imageWidth = options.OutWidth;
    
    var imageSource = ImageSource.FromStream(() => new MemoryStream(ImageByteArray, 0, ImageByteArray.Length));