using System; using System.Collections.Specialized; using System.IO; using System.Net; using System.Xml; namespace eBay_Images { struct ImgurResponse { // Raw response for logging or debugging. public string Raw { get; set; } public string Image { get; set; } public string Thumbnail { get; set; } } class ImgurV3 { public static string THUMBNAIL_SUFFIX = "t"; public static ImgurResponse Upload(byte[] image, string name) { var ret = new ImgurResponse(); var response = DoUpload(image, name); ret.Raw = GetUploadResponse(response); var xml = new XmlDocument(); xml.LoadXml(ret.Raw); ret.Image = GetDirectLink(xml); ret.Thumbnail = GetThumbnailLinkFromDirectLink(ret.Image); return ret; } private static string CLIENT_ID = "5a2f9a4c3da3908"; private static string ENDPOINT = "https://api.imgur.com/3/"; private static string ENDPOINT_IMAGE = ENDPOINT + "image.xml"; private static HttpWebResponse DoUpload(byte[] image, string name) { var spec = new UploadSpec(image, name, "image"); var headers = new NameValueCollection(); headers.Add("Authorization", String.Format("Client-ID {0}", CLIENT_ID)); var fields = new StringDictionary(); fields.Add("name", name); fields.Add("description", name); return HttpUpload.Upload(new Uri(ENDPOINT_IMAGE), headers, fields, null, null, spec); } private static string GetUploadResponse(HttpWebResponse response) { var reply = new StreamReader(response.GetResponseStream()); var str = reply.ReadToEnd(); return str; } private static string GetDirectLink(XmlDocument xml) { var link = xml.SelectSingleNode("//link"); if (link == null || link.InnerText == null || link.InnerText.Length == 0) throw new ApplicationException("link node has no value"); return link.InnerText; } private static string GetThumbnailLinkFromDirectLink(string link) { var uri = new UriBuilder(link); // Remove port if it is the default for http. if (uri.Scheme == "http" && uri.Port == 80) uri.Port = -1; var path = uri.Path; var filename = Path.GetFileNameWithoutExtension(path); var thumbFilename = filename + THUMBNAIL_SUFFIX; var thumbPath = path.Replace(filename, thumbFilename); uri.Path = thumbPath; return uri.ToString(); } } }