将对象转换为字节数组

时间:2019-04-01 00:56:34

标签: xamarin.ios

编辑:

很抱歉,您的回复很晚。

我尝试了答案中的代码,但是从Byte到Image的转换遇到了问题。

 public override void ViewDidLoad()
        {

            var image = UIImage.FromFile("image.png");

            var imageWidth = image.Size.Width;
            var imageHeight = image.Size.Height;

            var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            var fullfilename = Path.Combine(documents, "Image.json");

            // save json methode

            SaveImageJson(image, fullfilename);

            // read json methode

            var newImage = readImageJson(fullfilename, imageWidth, imageHeight);


        }


        public static void SaveImageJson(UIImage image, string fullfilename)
        {
            // Convert image to byteArray

            Byte[] imageByteArray = ReadFully(image.AsPNG().AsStream());


            // Serialize object
            var json = JsonConvert.SerializeObject(imageByteArray, Formatting.Indented);

            // Save to file

            File.WriteAllText(fullfilename, json);
        }

        public static byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

        public static UIImage readImageJson(string fullfilename, nfloat width, nfloat height)
        {

            var filenameNewImage = File.ReadAllText(fullfilename, System.Text.Encoding.ASCII);

            var jsonNewImage = JsonConvert.DeserializeObject(filenameNewImage);

            Byte[] ByteNewImage = ObjectToByteArray(jsonNewImage);


            UIImage NewImage = new UIImage();

            NewImage = ImageFromBytes(ByteNewImage, width, height);

            return NewImage;

        }


        public static byte[] ObjectToByteArray(Object obj)
        {
            BinaryFormatter bf = new BinaryFormatter();
            using (var ms = new MemoryStream())
            {
                bf.Serialize(ms, obj);
                return ms.ToArray();
            }
        }

        private static UIImage ImageFromBytes(byte[] bytes, nfloat width, nfloat height)
        {
            try
            {
                NSData data = NSData.FromArray(bytes);
                UIImage image = UIImage.LoadFromData(data);
                CGSize scaleSize = new CGSize(width, height);
                UIGraphics.BeginImageContextWithOptions(scaleSize, false, 0);
                image.Draw(new CGRect(0, 0, scaleSize.Width, scaleSize.Height));
                UIImage resizedImage = UIGraphics.GetImageFromCurrentImageContext();
                UIGraphics.EndImageContext();
                return resizedImage;
            }
            catch (Exception)
            {
                return null;
            }
        }

我在将对象转换为字节数组时遇到问题

我有一个Xamarin.IOS仿真,其中必须读取数据,该数据是使用Json方法之前保存的图像。我在回读数据时遇到问题,我认为它与转换有关。我使用一种方法将从Json文件中获取的对象转换为字节数组,因此我可以稍后将其转换为UIImage,不幸的是,该转换不起作用,因为当我比较保存的字节数组和我保存的字节数组时,从read方法中得到的,我发现它们是不同的

    public override void ViewDidLoad()
    {
        base.ViewDidLoad(); 
  // getting the file that we saved the data before

      var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        var filename = Path.Combine(documents, "account.json");
        File.WriteAllText(filename, json);
    var filename2 = File.ReadAllText(filename,System.Text.Encoding.ASCII);

        var json2 = ObjectToByteArray(JsonConvert.DeserializeObject(filename2));


        NSData data2 = NSData.FromArray(json2);

        UIImage image2 = new UIImage();
        image2 = UIImage.LoadFromData(data2);

        img.Image = image2;

    }

    public static byte[] ObjectToByteArray(Object obj)
    {
        BinaryFormatter bf = new BinaryFormatter();
        using (var ms = new MemoryStream())
        {
            bf.Serialize(ms, obj);
            return ms.ToArray();
        }
    }

1 个答案:

答案 0 :(得分:0)

使用其他转换。

首先,将您的UIImage转换为Stream。为此,请使用“ myUIImage.AsPng()。AsStream()”。然后将“流”转换为“字节数组”。为此,请使用:

public static byte[] ReadFully(Stream input)
{
    byte[] buffer = new byte[16*1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}

然后您可以安全地对其进行序列化。

要从字节数组制作图像,可以使用此扩展名

private UIImage ImageFromBytes(byte[] bytes, nfloat width, nfloat height)
{
    try {
        NSData data = NSData.FromArray(bytes);
        UIImage image = UIImage.LoadFromData(data);
        CGSize scaleSize = new CGSize(width, height);
        UIGraphics.BeginImageContextWithOptions(scaleSize, false, 0);
        image.Draw(new CGRect(0,0, scaleSize.Width, scaleSize.Height));
        UIImage resizedImage = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();
        return resizedImage;
    } catch (Exception) {
        return null;
    }
}

相信这会有所帮助。