0

我目前正在尝试构建一个应用程序,该应用程序涉及用户从他们的库中选择一张照片(或拍照)并将其上传到 Imgur。我已经为 Windows 窗体应用程序构建了一个相当强大的 C# Imgur 客户端,但不幸的是,将它移植到 Windows Phone 上是一场灾难。

这是我正在使用的代码:

public void UploadImageAsync(Stream PhotoStream)
{
    try
    {
        WebClient w = new WebClient();
        w.Headers["Content-type"] = "application/x-www-form-urlencoded";

        string data = "key="+PublicKey+
                "&_fake_status=200"+
                "&type=base64"+
                "&image="+PhotoStreamToBase64(PhotoStream);

        w.UploadStringAsync(new Uri("http://api.imgur.com/2/upload", UriKind.Absolute), "POST", data);

    }
    catch (Exception ex)
    {
    }
}

string PhotoStreamToBase64(Stream PhotoStream)
{
    MemoryStream memoryStream = new MemoryStream();
    PhotoStream.CopyTo(memoryStream);
    byte[] result = memoryStream.ToArray();
    return System.Convert.ToBase64String(result);
}

有趣(也令人沮丧)的是,似乎一切正常,上传完成后我收到了成功的响应。但是,上传后尝试查看图像时,结果如下所示:http://i.imgur.com/NWY0R.jpg

这使我相信图像流以某种方式被错误地转换为字节数组,或者被错误地转换为 base 64 字符串。无论如何,我无法让它工作,我完全不知所措。有人知道吗?任何帮助将不胜感激。

4

1 回答 1

1

SpikeX pushed me toward Imgur's C# API example for image uploading. Borrowing the Base64 encoding logic from their example fixed the issue. Here is the now functional PhotoStreamToBase64 method:

string PhotoStreamToBase64(Stream PhotoStream)
{
    MemoryStream memoryStream = new MemoryStream();
    PhotoStream.CopyTo(memoryStream);
    byte[] result = memoryStream.ToArray();

    string base64img = System.Convert.ToBase64String(result);
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < base64img.Length; i += 32766)
    {
        sb.Append(Uri.EscapeDataString(base64img.Substring(i, Math.Min(32766, base64img.Length - i))));
    }

    return sb.ToString();
}
于 2012-06-01T20:37:56.823 回答