3

I just recieve my unique developer API key from Imgur and I'm aching to start cracking on this baby.

First a simple test to kick things off. How can I upload an image using C#? I found this using Python:

#!/usr/bin/python

import pycurl

c = pycurl.Curl()
values = [
          ("key", "YOUR_API_KEY"),
          ("image", (c.FORM_FILE, "file.png"))]
# OR:     ("image", "http://example.com/example.jpg"))]
# OR:     ("image", "BASE64_ENCODED_STRING"))]

c.setopt(c.URL, "http://imgur.com/api/upload.xml")
c.setopt(c.HTTPPOST, values)

c.perform()
c.close()
Sergio Tapia
  • 40,006
  • 76
  • 183
  • 254

3 Answers3

4

looks like the site uses HTTP Post to upload images. Take a look at the HTTPWebRequest class and using it to POST to a URL: Posting data with HTTPRequest.

GrayWizardx
  • 19,561
  • 2
  • 30
  • 43
4

The Imgur API now provide a complete c# 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();

            string uploadRequestString = "image=" + Uri.EscapeDataString(System.Convert.ToBase64String(imageData)) + "&key=" + apiKey;

            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();
        }
    }
}
Michael Pereira
  • 1,263
  • 1
  • 17
  • 28
  • 2
    I've already seen this code before. It didn't work for me, and also the link you provided has been taken down. Imgur told me (I asked them) they took it down because the older examples were irrelevant because of the new API. – Ahmad Apr 23 '13 at 23:20
2

Why don't you use the NuGet for this: called Imgur.API and for upload you would have a method like this:

/*
   The refresh token and all the values represented by constans are given when you allow the application in your imgur panel on the response url
*/

public OAuth2Token CreateToken()
{
    var token = new OAuth2Token(TOKEN_ACCESS, REFRESH_TOKEN, TOKEN_TYPE, ID_ACCOUNT, IMGUR_USER_ACCOUNT, int.Parse(EXPIRES_IN));
    return token;
}

//Use it only if your token is expired
public Task<IOAuth2Token> RefreshToken()
{
    var client = new ImgurClient(CLIENT_ID, CLIENT_SECRET);
    var endpoint= new OAuth2Endpoint(client);
    var token = endpoint.GetTokenByRefreshTokenAsync(REFRESH_TOKEN);
    return token;
}


public async Task UploadImage()
{
     try
     {
          var client = new ImgurClient(CLIENT_ID, CLIENT_SECRET, CreateToken());
          var endpoint = new ImageEndpoint(client);
          IImage image;
          //Here you have to link your image location
          using (var fs = new FileStream(@"IMAGE_LOCATION", FileMode.Open))
          {
             image = await endpoint.UploadImageStreamAsync(fs);
          }
                Debug.Write("Image uploaded. Image Url: " + image.Link);
         }
         catch (ImgurException imgurEx)
         {
                Debug.Write("Error uploading the image to Imgur");
                Debug.Write(imgurEx.Message);
         }
     }

Also you can find all the reference here: Imgur.API NuGet

Carlos Valdez
  • 129
  • 1
  • 10