37 6
Top 1% !
Pearl of Wisdom
Popularity: 2713rd place

Published on:


Image upload to API, return direct link. (IMGUR)

Imgur, one of the best image hosts in the world, has a fantastic API, this is a VERY simple and usable implementation of it, just pass an image to the function and it will return the direct link to yout image, heavily commented and easy to use.
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
public string UploadImage(Image img) { //get a dev key from, anonymous usage (no user auth) only. string devkey = "YOUR_CLIENT_ID (e.g. abcde1f234567g8)"; //define the WebClient we'll use to communicate with Imgur. WebClient w = new WebClient(); //adds the Header to authorize this application with Imgur, must include a valid CLIENT_ID from 'devkey' above. w.Headers.Add("Authorization", "Client-ID " + devkey); System.Collections.Specialized.NameValueCollection Keys = new System.Collections.Specialized.NameValueCollection(); try { //Converts the image to a byte array so it can be turned into a string for upload. using (MemoryStream stream = new MemoryStream()) { img.Save(stream, ImageFormat.Png); Keys.Add("image", Convert.ToBase64String(stream.ToArray())); } //uploads the string-formatted-image and waits for the response. byte[] responseArray = w.UploadValues("", Keys); dynamic result = Encoding.ASCII.GetString(responseArray); //formats the (long and technical) result into just the direct image link. Regex reg = new Regex("link\":\"(.*?)\""); Match match = reg.Match(result); string url = match.ToString().Replace("link\":\"", "").Replace("\"", "").Replace("\\/", "/"); //returns the online address of the image. return url; } catch (Exception s) { MessageBox.Show(s.Message); return "err"; } }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus