Xamarin – Convert image to byte array

Published

I use a media plugin to take or pick a photo from either an Android device or iOS device. I then want to tweet that image using LINQtoTwitter. In order to do that the image needs to be in the format bytes[]. How would I convert my image to bytes in order to upload?

Code for getting Image

        takePhoto.Clicked += async (sender, args) =>
        {

            if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
            {
                  await DisplayAlert("No Camera", ":( No camera avaialble.", "OK");
                return;
            }

            var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
            {
                PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
                Directory = "Sample",
                Name = "test.jpg"
              });

            if (file == null)
                  return;

            await DisplayAlert("File Location", file.Path, "OK");

            temp2 = file.Path;

            image.Source = ImageSource.FromStream(() =>
            {
                  var stream = file.GetStream();
                  file.Dispose();
                  return stream;
            });
        };

        pickPhoto.Clicked += async (sender, args) =>
        {
            if (!CrossMedia.Current.IsPickPhotoSupported)
            {
                await DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
                return;
            }
            var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
            {
                PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium
            });


            if (file == null)
                return;

            image.Source = ImageSource.FromStream(() =>
            {
                  var stream = file.GetStream();
                  file.Dispose();
                  return stream;
            });
        };

Code for tweeting image

static async void SendTweetWithSinglePicture()
    {
        var auth = new SingleUserAuthorizer
        {
            CredentialStore = new SingleUserInMemoryCredentialStore
            {
                ConsumerKey = "KEY",
                ConsumerSecret = "KEY",
                AccessToken = "KEY",
                AccessTokenSecret = "KEY"
            }
        };

        var context = new TwitterContext(auth);


        var uploadedMedia = await context.UploadMediaAsync(IMAGE);

        var mediaIds = new List<ulong> { uploadedMedia.MediaID };

        await context.TweetAsync(
            "This is a test tweet",
            mediaIds
        );
    }

Any help would be much appreciated

FOUND SOLUTION

takePhoto.Clicked += async (sender, args) =>
        {

            if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
            {
                  await DisplayAlert("No Camera", ":( No camera avaialble.", "OK");
                return;
            }

            var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
            {
                PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
                Directory = "Sample",
                Name = "test.jpg"
              });

            if (file == null)
                  return;

            await DisplayAlert("File Location", file.Path, "OK");

            temp2 = file.Path;

            image.Source = ImageSource.FromStream(() =>
            {
                  var stream = file.GetStream();
                  return stream;
            });

            using (var memoryStream = new MemoryStream())
              {
                  file.GetStream().CopyTo(memoryStream);
                  file.Dispose();
                  imageAsBytes = memoryStream.ToArray();
              }
        };

static async void SendTweetWithSinglePicture()
    {
        var auth = new SingleUserAuthorizer
        {
            CredentialStore = new SingleUserInMemoryCredentialStore
            {
                ConsumerKey = "KEY",
                ConsumerSecret = "KEY",
                AccessToken = "KEY",
                AccessTokenSecret = "KEY"
            }
        };

        var context = new TwitterContext(auth);


        var uploadedMedia = await context.UploadMediaAsync(imageAsBytes, "image/jpg");

        var mediaIds = new List<ulong> { uploadedMedia.MediaID };

        await context.TweetAsync(
            "Hello World! I am testing @dougvdotcom's #LinqToTwitter demo, at " +
            "https://www.dougv.com/2015/08/posting-twitter-status-updates-tweets-with-linqtotwitter-and-net-part-3-media-tweets",
            mediaIds
        );
    }

Source: Xamarin.ios Questions

Published
Categorised as Uncategorised Tagged , , , ,

Answers

Image can not be converted to byte array , stream will be

image.Source = ImageSource.FromStream(() =>
            {
                  var stream = file.GetStream();
                  file.Dispose();
                  byte[] imgByteArray = ConvertStreamToByteArray(imgStream);
                  return stream;
            });

ConvertStreamToByteArray Method

public byte[] ConvertStreamToByteArray (System.IO.Stream stream)
        {
            long originalPosition = 0;

            if (stream.CanSeek)
            {
                originalPosition = stream.Position;
                stream.Position = 0;
            }

            try
            {
                byte[] readBuffer = new byte[4096];

                int totalBytesRead = 0;
                int bytesRead;

                while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
                {
                    totalBytesRead += bytesRead;

                    if (totalBytesRead == readBuffer.Length)
                    {
                        int nextByte = stream.ReadByte();
                        if (nextByte != -1)
                        {
                            byte[] temp = new byte[readBuffer.Length * 2];
                            Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                            Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                            readBuffer = temp;
                            totalBytesRead++;
                        }
                    }
                }

                byte[] buffer = readBuffer;
                if (readBuffer.Length != totalBytesRead)
                {
                    buffer = new byte[totalBytesRead];
                    Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
                }
                return buffer;
            }
            finally
            {
                if (stream.CanSeek)
                {
                    stream.Position = originalPosition;
                }
            }
        }

Arthur Erdman I

Leave a Reply

Your email address will not be published. Required fields are marked *

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq