Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set image from bitmap

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 contains method SetImageBitmap.
What the best way to set Xamarin.Forms.Image from my bitmap?

like image 929
Kirill Avatar asked Nov 10 '22 06:11

Kirill


1 Answers

Convert the Bitmap to byte[] via http://forums.xamarin.com/discussion/5950/how-to-convert-from-bitmap-to-byte-without-bitmap-compress

There are two solutions mentioned.

  1. var byteArray = ByteBuffer.Allocate(bitmap.ByteCount);
    bitmap.CopyPixelsToBuffer(byteArray);
    byte[] bytes = byteArray.ToArray<byte>();
    return bytes;
    
  2. (in case first solution is still broken)

    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);
    

And then use

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

to create an Image.

like image 150
Wosi Avatar answered Nov 14 '22 21:11

Wosi