by
37 6
1
6
350k
0
Top 1% !
Popular
Pearl of Wisdom
Easy-to-find
Specified
OpenSource
Popularity: 2713rd place

Published on:

LanguageCSharp
LicenseMIT_X11

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;"
src="https://www.snip2code.com/Embed/229532/Image-upload-to-API--return-direct-link-?startLine=0"></iframe>
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 api.imgur.com, 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("https://api.imgur.com/3/image", 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