从位图设置图像

时间:2015-08-19 10:07:00

标签: c# android xamarin xamarin.forms

Image image = new Image ();
Bitmap bitmap = Bitmap.CreateBitmap (200, 100, Bitmap.Config.Argb8888);
Canvas canvas = new Canvas(bitmap);

var paint = new Paint();
paint.Color = Android.Graphics.Color.Red;
paint.SetStyle(Paint.Style.Fill);

Rect rect = new Rect(0, 0, 200, 100);
canvas.DrawRect(rect, paint);

Android.Widget.ImageView 包含方法SetImageBitmap
从我的位图设置 Xamarin.Forms.Image 的最佳方法是什么?

2 个答案:

答案 0 :(得分:0)

通过http://forums.xamarin.com/discussion/5950/how-to-convert-from-bitmap-to-byte-without-bitmap-compress

Bitmap转换为byte[]

提到了两种解决方案。

  1. var byteArray = ByteBuffer.Allocate(bitmap.ByteCount);
    bitmap.CopyPixelsToBuffer(byteArray);
    byte[] bytes = byteArray.ToArray<byte>();
    return bytes;
    
  2. (如果第一个解决方案仍未解决)

    ByteBuffer buffer = ByteBuffer.Allocate(bitmap.ByteCount);
    bitmap.CopyPixelsToBuffer(buffer);
    buffer.Rewind();
    
    IntPtr classHandle = JNIEnv.FindClass("java/nio/ByteBuffer");
    IntPtr methodId = JNIEnv.GetMethodID(classHandle, "array", "()[B");
    IntPtr resultHandle = JNIEnv.CallObjectMethod(buffer.Handle, methodId);
    byte[] byteArray = JNIEnv.GetArray<byte>(resultHandle);
    JNIEnv.DeleteLocalRef(resultHandle);
    
  3. 然后使用

    var image = new Image();
    image.Source = ImageSource.FromStream(() => new MemoryStream(byteArray));
    

    创建Image

答案 1 :(得分:0)

I tried @Wosi's answer, but for some reason the rendering of the image after that didn't work and the code is specific to Android. I needed to work from a byte array to a bitmap and then back again. This is what I did:

Code for turning a bitmap into a byte array:

        byte[] bitmapData;
        using (var stream = new MemoryStream())
        {
            tempBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 0, stream);
            bitmapData = stream.ToArray();
        }

And the code for turning a byte array into a bitmap:

 Android.Graphics.Bitmap tempBitmap = Android.Graphics.BitmapFactory.DecodeByteArray(imageByteArray, 0, imageByteArray.Length, options);

Where "options" is defined as follows:

        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;

In this part the Bitmap gets decoded. This is done to get the image height and width properties. For my case I required this information to encode it as a byte array again.

There with this it is possible to encode a byte array to a string and then back again.

Setting an image source from a byte array is done as follows:

var imageSource = ImageSource.FromStream(() => new MemoryStream(ImageByteArray, 0, ImageByteArray.Length));