Image Uploaders

Discussion in 'Programming General' started by Flaming Idiots, Nov 21, 2008.

Image Uploaders
  1. Unread #1 - Nov 21, 2008 at 1:46 PM
  2. Flaming Idiots
    Joined:
    Dec 22, 2005
    Posts:
    235
    Referrals:
    1
    Sythe Gold:
    0
    Two Factor Authentication User

    Flaming Idiots Active Member
    Visual Basic Programmers

    Image Uploaders

    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:
    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;
        }
    }
    ImageShack Uploader:
    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;
        }
    }
    TinyPic Uploader:
    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;
        }
    }
    Here is how you upload an image:
    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();
    }
    
     
  3. Unread #2 - Jan 8, 2009 at 6:12 PM
  4. Jaex
    Joined:
    Jan 8, 2009
    Posts:
    8
    Referrals:
    0
    Sythe Gold:
    0

    Jaex Newcomer

    Image Uploaders

    I signed up to this site for thank you and ask one question.
    Your code working very nice. But i can't understand why are you using "var" for declare somethings instead write type name? I changed all "var" words to type name. Later i changed regexps for take direct image links example in Imageshack i did that :

    Code:
    string imgSource = PostImage(imgStream, "http://www.imageshack.us/index.php", "fileupload", GetMimeType(format),
                    arguments, cookies, "http://www.imageshack.us");
                result = Regex.Match(imgSource, "(?<=image_link>).+(?=</image_link)").Value;
    and in Tinypic i did that :

    Code:
    string imgSource = PostImage(imgStream, "http://s4.tinypic.com/upload.php", "the_file", GetMimeType(format),
                    arguments, cookies, "http://tinypic.com/");
                string imgIval = Regex.Match(imgSource, "(?<=ival\" value=\").+(?=\" />)").Value;
                string imgPic = Regex.Match(imgSource, "(?<=pic\" value=\").+(?=\" />)").Value;
                string imgType = Regex.Match(imgSource, "(?<=type\" value=\").*(?=\" />)").Value;
                if (imgType == "") imgType = ".jpg";
                result = "http://i" + imgIval + ".tinypic.com/" + imgPic + imgType;
    also i removed this for increase upload speed :

    Code:
    { "UPLOAD_IDENTIFIER", Regex.Match(mainPageHtml, "(?<=uid\" value=\").+(?=\" />)").Value },
                    { "upk", Regex.Match(mainPageHtml, "(?<=upk\" value=\").+(?=\" />)").Value },
    uid and upk not need for upload and i don't know what is thats. So I dont need to download mainpagehtml for get this values.

    My question is how can i use progress bar for show upload progress. This is important for my application. I'm creating multi image uploader with progress bars. I think this line uploading my image because i did some tests and in this line waiting too much:

    Code:
    WebResponse response = request.GetResponse();
    I tried to find solution in google but i'm not success :(
    I hope you can help me. Thank you again and sorry for my bad english :)

    Edit:
    I'm did some tests with timers and im wrong about this:

    Code:
    WebResponse response = request.GetResponse();
    Because this line completed in 1 second with tinypic and 5 second with imageshack. I think this line for download results.

    Code:
            while (true)
            {
                bytesRead = imageStream.Read(buffer, 0, buffer.Length);
                if (bytesRead == 0) break;
                requestStream.Write(buffer, 0, bytesRead);
            }
    Thats completed in 55 second with tinypic ( for 1.5mb image ) and 35 second with imageshack.
    So i can make progress bar easily in this loop.
    I think my problem solved :D

    Edit 2:

    I added progress bar like that :

    Code:
            int bytesRead = 0;
            int bytesReadTotal = 0;
            while (true)
            {
                bytesRead = imageStream.Read(buffer, 0, buffer.Length);
                if (bytesRead == 0) break;
                requestStream.Write(buffer, 0, bytesRead);
                bytesReadTotal += bytesRead;
                Console.SetCursorPosition(0, Console.CursorTop);
                Console.Write(100 * bytesReadTotal / (int)imageStream.Length + "%");
            }
    but still need progress bar for this line :

    Code:
    WebResponse response = request.GetResponse();
    Because if im uploading little image, upload operation completing very fast but in this line i need to wait 2-5 second :(
     
  5. Unread #3 - Jan 16, 2009 at 10:44 PM
  6. McoreD
    Joined:
    Jan 16, 2009
    Posts:
    2
    Referrals:
    0
    Sythe Gold:
    0

    McoreD Newcomer

    Image Uploaders

    This is some amazing code. Thank you for this.

    With similar goals in mind, we have been building an open source ImageUploader.dll that will ultimately include all the free image uploads, accessible in one DLL. So we had ImageShack already. TinyPic is a great addition!

    The primary tester application is a Screenshotting app called ZScreen.

    The code compiles all great, but when you upload an image to TinyPic, the result is "http://tinypic.com"

    TinyPicUploader:
    http://zscreen.svn.sourceforge.net/.../ImageUploader/TinyPicUploader.cs?view=markup

    For your referecnce, ImageShackUploader:
    http://zscreen.svn.sourceforge.net/...ageUploader/ImageShackUploader.cs?view=markup


    I was hoping you could point us in the right direction. :)

    Thanks,
    McoreD


    Edit:

    I keep getting

    for TinyPic. :(
     
  7. Unread #4 - Jan 17, 2009 at 5:47 PM
  8. Solarsonic88
    Joined:
    Oct 19, 2008
    Posts:
    50
    Referrals:
    0
    Sythe Gold:
    0

    Solarsonic88 Member
    Banned

    Image Uploaders

    Thanks for this. Good work!
     
  9. Unread #5 - Jan 18, 2009 at 8:35 AM
  10. Jaex
    Joined:
    Jan 8, 2009
    Posts:
    8
    Referrals:
    0
    Sythe Gold:
    0

    Jaex Newcomer

    Image Uploaders

    I think something changed in tinypic main page and i can't find what is wrong.
    I used tinypic plugin page for upload pictures. http://plugin.tinypic.com/plugin/index.php

    Source code:

    http://paste2.org/p/131686
     
  11. Unread #6 - Jan 20, 2009 at 5:00 AM
  12. McoreD
    Joined:
    Jan 16, 2009
    Posts:
    2
    Referrals:
    0
    Sythe Gold:
    0

    McoreD Newcomer

    Image Uploaders

    Thanks Jaex, that works great! I tested it. See you online.
     
  13. Unread #7 - Jun 23, 2009 at 8:11 AM
  14. mxdev
    Joined:
    Jun 23, 2009
    Posts:
    1
    Referrals:
    0
    Sythe Gold:
    0

    mxdev Newcomer

    Image Uploaders


    I got the same error after copying that code.

    then i changed it a little:

    1. parameters
    missed a space between name="upk" and value in Regex expression for parsng upk field.

    also added addresses field, shareopt is true, changed MAX_FILE_SIZE

    so the parameters are now:

    Dictionary<string, string> arguments = new Dictionary<string, string>();
    arguments.Add("UPLOAD_IDENTIFIER", ident = Regex.Match(mainPageHtml, @"<input type=""hidden"" name=""UPLOAD_IDENTIFIER"" id=""uid"" value=""([^""]+)"" />").Groups[1].Value);
    arguments.Add("upk", upk = Regex.Match(mainPageHtml, @"<input type=""hidden"" name=""upk"" value=""([^""]+)"" />").Groups[1].Value);
    arguments.Add("domain_lang", "en");
    arguments.Add("action", "upload");
    arguments.Add("MAX_FILE_SIZE", "500000000");
    arguments.Add("shareopt", "true");
    arguments.Add("description", "");
    arguments.Add("file_type", "image");
    arguments.Add("dimension", "1600");
    arguments.Add("video-settings", "sd");
    arguments.Add("addresses", "");


    2. also to get url of the image i need to get an extra HTML page like this:

    string response = PostImage(imgStream, "http://s4.tinypic.com/upload.php", "the_file", GetMimeType(format), arguments, cookies, "http://tinypic.com/");


    string u1 = Regex.Match(response, @"<a href=""([^""]+)"" target=""_blank"">").Groups[1].Value;

    WebClient webClient2 = new WebClient();
    string viewPageHtml = webClient2.DownloadString(u1);
    webClient2.Dispose();

    string urlDirect = Regex.Match(viewPageHtml,
    @"<input type=""text"" class=""input-link"" id=""direct-url"" value=""([^""]+)""").Groups[1].Value;

    result = new Uri(urlDirect);



    this code works for me now.


    --------------

    http://mxdev.blogspot.com
    http://mxdev.biz
     
  15. Unread #8 - Jul 22, 2009 at 4:39 AM
  16. liammc123
    Joined:
    Jul 7, 2008
    Posts:
    69
    Referrals:
    0
    Sythe Gold:
    0

    liammc123 Member

    Image Uploaders

    One or more errors encountered while loading the designer. The errors are listed below. Some errors can be fixed by rebuilding your project, while others may require code changes.

    The designer could not be shown for this file because none of the classes within it can be designed. The designer inspected the following classes in the file: ImageUploaderBase --- The base class 'System.Object' cannot be designed. Form1 --- The base class 'System.Object' cannot be designed.
    Hide

    at System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.EnsureDocument(IDesignerSerializationManager manager)
    at System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager manager)
    at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager serializationManager)
    at System.ComponentModel.Design.Serialization.BasicDesignerLoader.BeginLoad(IDesignerLoaderHost host)

    thats coming up
     
  17. Unread #9 - Aug 8, 2010 at 5:53 PM
  18. DMW007
    Joined:
    Apr 15, 2010
    Posts:
    1
    Referrals:
    0
    Sythe Gold:
    0

    DMW007 Newcomer

    Image Uploaders

    Your idea with the classes are nice, i did somethink like this too.
    But some times you can make your code more easy, like in the following line:

    Code:
    var boundaryBytes = Encoding.ASCII.GetBytes("\n--" + boundary + "\n");
    
    Why do you convert the boundary into a byte? I think its much more easy to put the complete content, header include, into a string and then in the end convert the complete string into a byte array and write them into the stream.

    Of course, you can also use photohosters where require logging. Mostly you can do this with the HttpWebRequest-Method, but sometimes this doesn't work, then you have to use Sockets or a TcpClient.
     
  19. Unread #10 - Aug 29, 2010 at 11:49 PM
  20. x0r0hail0x
    Joined:
    Aug 29, 2010
    Posts:
    1
    Referrals:
    0
    Sythe Gold:
    0

    x0r0hail0x Newcomer
    Banned

    Image Uploaders

    efefmantas yra kietas
     
< Omegle Auto Talker | WinRar KeyGen >

Users viewing this thread
1 guest


 
 
Adblock breaks this site