Reputation Top 5%
1 Snippet  (618th place)
1 Channel
1 Channel
37 points  (769th place)
Junior Code Generator
Junior Publisher
Junior Judge
Junior Popular Coder
Junior Autobiographer
Junior Wise Coder

Recent Snippets See all snippets by clsw

public by clsw  350041  0  6  1

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.
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();
                //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"; }