Twitter image Downloader

特定ユーザーのTwitterのすべての写真をダウンロード

Twitter image Downloadertwitterdownloader

Twitter image Downloaderダウンロードはこちら

ソースコードはこちらです。

Form1.cs

[html]
<div id="sourceContentPlaceHolder">
<div id="sourceBrowserContainer">
<div id="splitView">
<div id="rightPane">
<div id="FileContentView">
<div id="FileView">
<div id="FileViewContainer">
<div>
<div id="fileContent">
<div>
<pre>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Xml;
using System.Security.Cryptography;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;

namespace TwitterImageDownloader
{
public partial class Form1 : Form
{
delegate void AddImageHandler(Image image);//The delegate

public Form1()
{
InitializeComponent();
listView1.View = View.LargeIcon;
imageList1.ImageSize = new Size(150, 150);
listView1.LargeImageList = this.imageList1;
}

private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(getImages));
t.Start();
}

private void getImages()
{
String userTimelineUrl = @"http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=" + tbScreenName.Text + @"&count=200&trim_user=1&exclude_replies=1&include_rts=0";
//String tweetUrl = @"http://api.twitter.com/1/statuses/show.xml?trim_user=1&include_entities=1&id=";

////First lets get the users tweets
WebClient webClient = new WebClient();
String userTimeLine = webClient.DownloadString(userTimelineUrl);
XmlDocument doc = new XmlDocument();
doc.LoadXml(userTimeLine);
XmlNodeList tweetList = doc.SelectNodes("//status");
foreach (XmlNode tweet in tweetList)
{
String tweetID = tweet.SelectSingleNode("id").InnerText;
String TweetText = tweet.SelectSingleNode("text").InnerText;

Match m = Regex.Match(TweetText, @"(?<twitterURL>t.co)/(?<subdir>[^\s]*)");
if (m.Success)
{
try
{
var request = (HttpWebRequest)WebRequest.Create(new Uri(@"http://t.co/" + m.Groups["subdir"].Value));
request.Method = "HEAD";
request.AllowAutoRedirect = false;

string location;
using (var response = request.GetResponse() as HttpWebResponse)
{
location = response.GetResponseHeader("Location");
}
string imageURL = String.Empty;

request = (HttpWebRequest)WebRequest.Create(location);

using (var response = request.GetResponse() as HttpWebResponse)
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
List<ImgTag> images = GetImageTags(sr.ReadToEnd());
sr.Close();
foreach (ImgTag image in images)
{

if (location.StartsWith("http:/") && location.IndexOf("/photo/") > -1)
{
//For twitter.com look for media-slideshow-image
if (image.classAtt == "large media-slideshow-image")
{
imageURL = image.src;
}
}
if (location.StartsWith("http://instagr.am"))
{
//For instagram look for for the image tag
if (image.classAtt == "photo")
{
imageURL = image.src;
}

}
}
}
}
if (imageURL != String.Empty)
{
//found an Image
Image img = LoadImage(imageURL, tweetID);
listView1.Invoke(new AddImageHandler(ImageThread),new object[]{img});
}
}
catch (Exception ex)
{
//skip tweet
Console.WriteLine(ex.Message);
}
}

}
MessageBox.Show("Done.");
}

private void ImageThread(Image img)
{
imageList1.Images.Add(img);
ListViewItem item = new ListViewItem();
item.ImageIndex = listView1.Items.Count + 1;
listView1.Items.Add(item);
listView1.Refresh();
}

private List<ImgTag> GetImageTags(String html)
{
List<ImgTag> imgTags = new List<ImgTag>();
MatchCollection m1 = Regex.Matches(html, @"(<img.*?>.*?>)", RegexOptions.Singleline);
foreach (Match m in m1)
{
string value = m.Groups[1].Value;
ImgTag imgTag = new ImgTag();
Match m2 = Regex.Match(value, @"src=\""(.*?)\""", RegexOptions.Singleline);
if (m2.Success)
{
imgTag.src = m2.Groups[1].Value;
}
m2 = Regex.Match(value, @"class=\""(.*?)\""", RegexOptions.Singleline);
if (m2.Success)
{
imgTag.classAtt = m2.Groups[1].Value;
}
imgTags.Add(imgTag);
}
return imgTags;
}

private class ImgTag {
public String src = String.Empty;
public String classAtt = String.Empty;
}

private Image LoadImage(string url,string tweetID)
{
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(Environment.CurrentDirectory.ToString(), tbScreenName.Text));
String fileLocation = System.IO.Path.Combine(Environment.CurrentDirectory.ToString(), tbScreenName.Text, tweetID + ".jpg");
using (var wc = new System.Net.WebClient())
{
wc.DownloadFile(url, fileLocation);
}
Bitmap bmp = new Bitmap(fileLocation);

return bmp;
}
}
}</pre>
</div>
</div>
</div>
</div>
</div>
</div>
<div></div>
</div>
</div>
<div></div>
</div>
</div>
<div></div>
<div id="footer"></div>
[/html]

Form1.Designer.cs

[html]namespace TwitterImageDownloader { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support – do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.tbScreenName = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.listView1 = new System.Windows.Forms.ListView(); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.SuspendLayout(); // // tbScreenName // this.tbScreenName.Location = new System.Drawing.Point(97, 12); this.tbScreenName.Name = "tbScreenName"; this.tbScreenName.Size = new System.Drawing.Size(216, 20); this.tbScreenName.TabIndex = 0; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(13, 13); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(72, 13); this.label1.TabIndex = 1; this.label1.Text = "Screen Name"; // // button1 // this.button1.Location = new System.Drawing.Point(367, 10); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 2; this.button1.Text = "Download"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // listView1 // this.listView1.Location = new System.Drawing.Point(12, 39); this.listView1.Name = "listView1"; this.listView1.Size = new System.Drawing.Size(638, 555); this.listView1.TabIndex = 8; this.listView1.UseCompatibleStateImageBehavior = false; // // imageList1 // this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit; this.imageList1.ImageSize = new System.Drawing.Size(16, 16); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(670, 604); this.Controls.Add(this.listView1); this.Controls.Add(this.button1); this.Controls.Add(this.label1); this.Controls.Add(this.tbScreenName); this.Name = "Form1"; this.Text = "TwitterDownloader – CodeBetweenTheLines.com"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox tbScreenName; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button button1; private System.Windows.Forms.ListView listView1; private System.Windows.Forms.ImageList imageList1; } }[/html]

Form1.resx

[html]
<div id="sourceContentPlaceHolder">
<div id="sourceBrowserContainer">
<div id="splitView">
<div id="rightPane">
<div id="FileContentView">
<div id="FileView">
<div id="FileViewContainer">
<div>
<div id="fileContent">
<div>
<pre><?xml version="1.0" encoding="utf-8"?>
<root>
<!–
Microsoft ResX Schema

Version 2.0

The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.

Example:

… ado.net/XML headers & schema …
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, …</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, …</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>

There are any number of "resheader" rows that contain simple
name/value pairs.

Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don’t support this are serialized and stored with the
mimetype set.

The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:

Note – application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.

mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.

mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
–>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="imageList1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root></pre>
</div>
&nbsp;
<pre></pre>
&nbsp;

</div>
</div>
</div>
</div>
</div>
<div></div>
</div>
</div>
<div></div>
</div>
</div>
<div></div>
<div id="footer"></div>
[/html]

Program.cs

[html]using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace TwitterImageDownloader { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }[/html]

TwitterImageDownloader.csproj

[html]<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" ‘$(Configuration)’ == ” ">Debug</Configuration> <Platform Condition=" ‘$(Platform)’ == ” ">x86</Platform> <ProductVersion>8.0.30703</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{41AD11AE-D2B5-48DC-BE79-13062E82C6C5}</ProjectGuid> <OutputType>WinExe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>TwitterImageDownloader</RootNamespace> <AssemblyName>TwitterImageDownloader</AssemblyName> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <TargetFrameworkProfile>Client</TargetFrameworkProfile> <FileAlignment>512</FileAlignment> <SccProjectName>SAK</SccProjectName> <SccLocalPath>SAK</SccLocalPath> <SccAuxPath>SAK</SccAuxPath> <SccProvider>SAK</SccProvider> </PropertyGroup> <PropertyGroup Condition=" ‘$(Configuration)|$(Platform)’ == ‘Debug|x86’ "> <PlatformTarget>x86</PlatformTarget> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" ‘$(Configuration)|$(Platform)’ == ‘Release|x86’ "> <PlatformTarget>x86</PlatformTarget> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Xml.Linq" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="Microsoft.CSharp" /> <Reference Include="System.Data" /> <Reference Include="System.Deployment" /> <Reference Include="System.Drawing" /> <Reference Include="System.Windows.Forms" /> <Reference Include="System.Xml" /> </ItemGroup> <ItemGroup> <Compile Include="Form1.cs"> <SubType>Form</SubType> </Compile> <Compile Include="Form1.Designer.cs"> <DependentUpon>Form1.cs</DependentUpon> </Compile> <Compile Include="Program.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <EmbeddedResource Include="Form1.resx"> <DependentUpon>Form1.cs</DependentUpon> </EmbeddedResource> <EmbeddedResource Include="Properties\Resources.resx"> <Generator>ResXFileCodeGenerator</Generator> <LastGenOutput>Resources.Designer.cs</LastGenOutput> <SubType>Designer</SubType> </EmbeddedResource> <Compile Include="Properties\Resources.Designer.cs"> <AutoGen>True</AutoGen> <DependentUpon>Resources.resx</DependentUpon> </Compile> <None Include="Properties\Settings.settings"> <Generator>SettingsSingleFileGenerator</Generator> <LastGenOutput>Settings.Designer.cs</LastGenOutput> </None> <Compile Include="Properties\Settings.Designer.cs"> <AutoGen>True</AutoGen> <DependentUpon>Settings.settings</DependentUpon> <DesignTimeSharedInput>True</DesignTimeSharedInput> </Compile> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!– To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> –> </Project>[/html]

TwitterImageDownloader.csproj.vspscc

[html]""
{
"FILE_VERSION" = "9237"
"ENLISTMENT_CHOICE" = "NEVER"
"PROJECT_FILE_RELATIVE_PATH" = ""
"NUMBER_OF_EXCLUDED_FILES" = "0"
"ORIGINAL_PROJECT_FILE_PATH" = ""
"NUMBER_OF_NESTED_PROJECTS" = "0"
"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER"
}[/html]