Xamarin - 将图像转换为字节数组

时间:2017-04-19 15:11:58

标签: c# xamarin xamarin.ios xamarin.android xamarin.forms

我使用媒体插件从Android设备或iOS设备中拍摄或选择照片。然后,我想使用LINQtoTwitter发布该图像。为此,图像需要采用bytes []格式。如何将我的图像转换为字节以便上传?

获取图片的代码

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

推特图片代码

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

非常感谢任何帮助

找到解决方案

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

1 个答案:

答案 0 :(得分:1)

图像无法转换为字节数组,流将变为

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

ConvertStreamToByteArray方法

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