【问题标题】:Base64 from e.ChosenPhoto apparently corrupted来自 e.ChosenPhoto 的 Base64 显然已损坏
【发布时间】:2013-04-14 12:28:19
【问题描述】:
            //convert photo to baos
            var memoryStream = new System.IO.MemoryStream();
            e.ChosenPhoto.CopyTo(memoryStream);
            //string baos = memoryStream.ToString();
            byte[] result = memoryStream.ToArray();
            String base64 = System.Convert.ToBase64String(result);
            String post_data = "&image=" + base64;
            ...
            wc.UploadStringAsync(imgur_api,"POST",post_data);  

我正在使用此代码通过 WebClient 将图像上传到 Imgur API v3。选择的图像是 Windows Phone 7.1 模拟器提供的 7 张照片之一,或者是模拟的相机图像。当我尝试加载图像时,它们大部分是灰色的损坏的混乱。我是否正确生成了 base64 和/或在创建 byte[] 和 base64 之前是否需要先渲染图片的位图?

提前致谢!

【问题讨论】:

标签: c# windows-phone-7 imgur


【解决方案1】:

我用这个

 private void PhotoChooserTaskCompleted(object sender, PhotoResult e)
    {
        if (e.TaskResult != TaskResult.OK) return;
        var bimg = new BitmapImage();
        bimg.SetSource(e.ChosenPhoto);
        var sbytedata = ReadToEnd(e.ChosenPhoto);
    }

 public static byte[] ReadToEnd(System.IO.Stream stream)
    {
        long 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
        {
            stream.Position = originalPosition;
        }
    }

并将byte[] 上传到服务器。希望对你有帮助

【讨论】:

    【解决方案2】:

    使用 Uri.EscapeDataString 之类的东西来转义数据,这样特殊的 URL 字符就不会被解释。

    【讨论】:

    • 这解决了问题,我使用的是我Android版本的基本逻辑,不需要转义base64数据(baos -> base64 -> post请求)
    猜你喜欢
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 2020-02-11
    • 1970-01-01
    相关资源
    最近更新 更多