Here are some image uploaders I wrote/re-wrote. If you can think of any other uploaders that do not require logging in ( like PhotoBucket or Flickr) I should be able to make them. To use any uploader, you must copy the required code into your project once for it to work, then copy the code for the uploader you want below it. You also need to have .NET 3.5 SP1 installed for the code to work.
Required Code:
ImageShack Uploader:
TinyPic Uploader:
Here is how you upload an image:
Required Code:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
public abstract class ImageUploaderBase
{
public abstract string Name { get; }
protected string GetMimeType(ImageFormat format)
{
foreach (var codec in ImageCodecInfo.GetImageDecoders())
if (codec.FormatID == format.Guid) return codec.MimeType;
return "image/unknown";
}
protected string GetMimeType(Image image)
{
return GetMimeType(image.RawFormat);
}
public abstract Uri UploadImage(Image image, ImageFormat format);
public Uri UploadImage(Image image)
{
return UploadImage(image, image.RawFormat);
}
public Uri UploadImage(string Path)
{
return UploadImage(Image.FromFile(Path));
}
protected string PostImage(Stream imageStream, string uploadUrl, string fileFormName, string contentType,
IDictionary<string, string> arguments, CookieContainer cookies, string referer)
{
string postData = arguments.Aggregate("?", (current, arg) => current + arg.Key + "=" + arg.Value + "&"); ;
Uri postUri = new Uri(uploadUrl + postData.Substring(0, postData.Length - 1));
string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
string postHeader = string.Format("--{0}\nContent-Disposition: form-data; name=\"{1}\"; filename=\"image\"\nContent-Type: {2}\n\n",
boundary, fileFormName ?? "file", contentType ?? "application/octet-stream");
var request = WebRequest.Create(postUri) as HttpWebRequest;
request.CookieContainer = cookies;
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; SV1; .NET CLR 2.0.50727; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
request.Referer = referer;
var postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
var boundaryBytes = Encoding.ASCII.GetBytes("\n--" + boundary + "\n");
request.ContentLength = postHeaderBytes.Length + imageStream.Length + boundaryBytes.Length;
var requestStream = request.GetRequestStream();
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
var buffer = new byte[((int)Math.Min(4096, imageStream.Length)) - 1];
int bytesRead = 0;
while (true)
{
bytesRead = imageStream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0) break;
requestStream.Write(buffer, 0, bytesRead);
}
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
var responseReader = new StreamReader(responseStream);
var returnValue = responseReader.ReadToEnd();
responseStream.Close();
return returnValue;
}
}
Code:
// Based off http://social.msdn.microsoft.com/forums/en-US/netfxnetcom/thread/03efc98c-68e2-410c-bf25-d5facacbd920/
// The Email property allows you to upload images directly to someones account.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
public sealed class ImageShackUploader : ImageUploaderBase
{
public override string Name
{
get { return "ImageShack"; }
}
public string Email { get; set; }
public override Uri UploadImage(Image image, ImageFormat format)
{
var imgStream = new MemoryStream();
image.Save(imgStream, format);
imgStream.Position = 0;
var oldValue = ServicePointManager.Expect100Continue;
Uri result = null;
try
{
ServicePointManager.Expect100Continue = false;
var cookies = new CookieContainer();
var arguments = new Dictionary<string, string>()
{
{ "MAX_FILE_SIZE", "3145728" },
{"refer", ""},
{"brand", ""},
{"optimage", "1"},
{"rembar", "1"},
{"submit", "host it!"},
{"optsize", "resample"},
{"xml", "yes"}
};
if (!string.IsNullOrEmpty(Email)) arguments.Add("email", Email);
result = new Uri(
XDocument.Parse(PostImage(imgStream, "http://www.imageshack.us/index.php", "fileupload", GetMimeType(format),
arguments, cookies, "http://www.imageshack.us/")).Elements(XName.Get("links")).Elements(XName.Get("done_page")).First().Value);
}
finally
{ ServicePointManager.Expect100Continue = oldValue; }
imgStream.Dispose();
return result;
}
}
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
public sealed class TinyPicUploader : ImageUploaderBase
{
public override string Name
{
get { return "TinyPic"; }
}
public override Uri UploadImage(Image image, ImageFormat format)
{
var imgStream = new MemoryStream();
image.Save(imgStream, format);
imgStream.Position = 0;
var oldValue = ServicePointManager.Expect100Continue;
Uri result = null;
try
{
ServicePointManager.Expect100Continue = false;
var cookies = new CookieContainer();
var webClient = new WebClient();
var mainPageHtml = webClient.DownloadString("http://tinypic.com/");
webClient.Dispose();
var arguments = new Dictionary<string, string>()
{
{ "UPLOAD_IDENTIFIER", Regex.Match(mainPageHtml, @"<input type=""hidden"" name=""UPLOAD_IDENTIFIER"" id=""uid"" value=""([^""]+)"" />" ).Groups[1].Value },
{ "upk", Regex.Match(mainPageHtml, @"<input type=""hidden"" name=""upk""id=""uid"" value=""([^""]+)"" />" ).Groups[1].Value },
{ "domain_lang", "en" },
{ "action", "upload" },
{ "MAX_FILE_SIZE", "200000000" },
{"shareopt", "false"},
{"description", ""},
{"file_type", "image"},
{"dimension", "1600"}
};
result = new Uri(
Regex.Match(PostImage(imgStream, "http://s4.tinypic.com/upload.php", "the_file", GetMimeType(format),
arguments, cookies, "http://tinypic.com/"), @"<a href=""([^""]+)"" target=""_blank"">").Groups[1].Value);
}
finally
{ ServicePointManager.Expect100Continue = oldValue; }
imgStream.Dispose();
return result;
}
}
Code:
private void UploadButton_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog(this) == DialogResult.Cancel) return;
var uploader = new TinyPicUploader(); // Replace with any uploader
this.UrlBox.Text = (uploader.UploadImage(openFileDialog.FileName) ?? (object)"Could not upload").ToString();
}



