Forum Xamarin.Forms
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

Set image from bitmap

KirillRadchenkoKirillRadchenko RUMember ✭✭
edited August 2015 in 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 contains method SetImageBitmap.
What the best way to set Xamarin.Forms.Image from my bitmap?

Tagged:

Best Answer

Answers

  • KirillRadchenkoKirillRadchenko RUMember ✭✭
    edited August 2015

    http://stackoverflow.com/questions/32092476/set-image-from-bitmap

    Java.Nio.ByteBuffer buffer = Java.Nio.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);
    
    var stream = new MemoryStream(byteArray);
    image.Source = ImageSource.FromStream(stream);
    

    Is this the best way?

  • adamkempadamkemp USInsider, Developer Group Leader mod

    That code is obviously platform-specific. This kind of thing can't be done in a PCL in a cross-platform way. You will have to use a DependencyService to implement this feature so that you can do the platform-specific code in the platform-specific project.

  • KirillRadchenkoKirillRadchenko RUMember ✭✭

    OK, but how I can set data in my image from the bitmap in cross-platform situation? I can't find this information

  • KirillRadchenkoKirillRadchenko RUMember ✭✭

    OK. Thanks for the help!

  • ahmedkhanahmedkhan USUniversity ✭✭

    Is there some code or example available as a working solution to this?? I have been search for a way to convert an Android Bitmap image to Xamarin.Forms ImageSource

  • This is coming late but can be useful to anyone who needs it now:

    @adamkemp said:
    The actual code that deals with the bitmap has to be in platform-specific code. You can write a DependencyService that gives you a Stream, and you can use that stream in the PCL. What you can't do in the PCL is actually draw the bitmap. That requires platform-specific APIs.

    I created a Github gist that implements what @adamkemp described above

Sign In or Register to comment.