动态获取上传图片的网址给Imgur

时间:2012-08-03 08:40:16

标签: c# visual-studio-2010 c#-4.0

我想使用它的API作为匿名用户将图像上传到Imgur.com。上传图片后,我想动态获取该图片网址。如何使用C#Winforms实现这一目标?

1 个答案:

答案 0 :(得分:1)

文档提供了您可以尝试的an example

using System;
using System.IO;
using System.Net;
using System.Text;

namespace ImgurExample
{
    class Program
    {
        static void Main(string[] args)
        {
            PostToImgur(@"C:\Users\ashwin\Desktop\image.jpg", IMGUR_ANONYMOUS_API_KEY);
        }

        public static void PostToImgur(string imagFilePath, string apiKey)
        {
            byte[] imageData;

            FileStream fileStream = File.OpenRead(imagFilePath);
            imageData = new byte[fileStream.Length];
            fileStream.Read(imageData, 0, imageData.Length);
            fileStream.Close();

            const int MAX_URI_LENGTH = 32766;
            string base64img = System.Convert.ToBase64String(imageData);
            StringBuilder sb = new StringBuilder();

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

            string uploadRequestString = "image=" + sb.ToString() + "&key=" + imgurApiKey;

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://api.imgur.com/2/upload");
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ServicePoint.Expect100Continue = false;

            StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream());
            streamWriter.Write(uploadRequestString);
            streamWriter.Close();

            WebResponse response = webRequest.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader responseReader = new StreamReader(responseStream);

            string responseString = responseReader.ReadToEnd();
        }
    }
}

服务器返回的响应将包含指向上传图像的链接。例如:

{
    "upload": {
        "image": {
            "name": false,
            "title": "",
            "caption": "",
            "hash": "cSNjk",
            "deletehash": "ZnKGru1reZKoabU",
            "datetime": "2010-08-16 22:43:22",
            "type": "image\/jpeg",
            "animated": "false",
            "width": 720,
            "height": 540,
            "size": 46174,
            "views": 0,
            "bandwidth": 0
        },
        "links": {
            "original": "http:\/\/imgur.com\/cSNjk.jpg",
            "imgur_page": "http:\/\/imgur.com\/cSNjk",
            "delete_page": "http:\/\/imgur.com\/delete\/ZnKGru1reZKoabU",
            "small_square": "http:\/\/imgur.com\/cSNjks.jpg",
            "large_thumbnail": "http:\/\/imgur.com\/cSNjkl.jpg"
        }
    }
}

要使用匿名API,您需要obtain an API key