Xamarin - 将图像转换为字节数组 [英] Xamarin - Convert image to byte array

查看:35
本文介绍了Xamarin - 将图像转换为字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

获取图片的代码

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

推荐答案

图片无法转字节数组,流会

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 方法

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

这篇关于Xamarin - 将图像转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆