<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>My Corner &#187; Programming</title>
	<atom:link href="http://blog.spencerkellis.net/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.spencerkellis.net</link>
	<description>An experiment in writing of life as I live it</description>
	<lastBuildDate>Sun, 27 Jun 2010 18:24:58 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Using Perl and ExifTool to Access EXIF Data in Digital Images</title>
		<link>http://blog.spencerkellis.net/2009/09/using-perl-and-exiftool-to-access-exif-data-in-digital-images/</link>
		<comments>http://blog.spencerkellis.net/2009/09/using-perl-and-exiftool-to-access-exif-data-in-digital-images/#comments</comments>
		<pubDate>Thu, 03 Sep 2009 02:03:29 +0000</pubDate>
		<dc:creator>Spencer</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[exif]]></category>
		<category><![CDATA[ExifTool]]></category>
		<category><![CDATA[JPG]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[RAW]]></category>

		<guid isPermaLink="false">http://blog.spencerkellis.net/?p=357</guid>
		<description><![CDATA[Overview EXIF data in digital images is a fairly complete snapshot of all camera and flash settings at the time of exposure. The information can be extremely useful in many ways, such as automatic image organization; metadata repositories for advanced searching; and unique file renaming, to name a few. In fact, Nikon NEF files have [...]]]></description>
			<content:encoded><![CDATA[<h2>Overview</h2>
<p>EXIF data in digital images is a fairly complete snapshot of all camera and flash settings at the time of exposure. The information can be extremely useful in many ways, such as automatic image organization; metadata repositories for advanced searching; and unique file renaming, to name a few. In fact, Nikon NEF files have a full-size Basic JPG image stored in the EXIF information, along with a thumbnail-sized preview.  Because of this, I never shoot RAW+JPG, since I get that JPG for free with every RAW file anyway — I just have to extract it.  This article documents how to access this and other data using Perl and the ExifTool package, written by Phil Harvey (documented on his website, <a href="http://www.sno.phy.queensu.ca/~phil/exiftool/" target="_blank">http://www.sno.phy.queensu.ca/~phil/exiftool/</a>). Both are available as free downloads for several platforms, including Linux and Windows XP.  I have used both packages on both platforms.</p>
<h2>Reading Data</h2>
<p>In order to use the package, it must be included at the top of the perl file:</p>
<pre class="perl">#!/usr/bin/perl -w
use Image::ExifTool;</pre>
<p>Reading data is fairly simple once a general process is established.  Information is organized for the most part in a &#8220;key/value&#8221; structure, like a hash in perl (and in fact, data returned by the exiftool object is represented by a hash structure).  The following perl code reads the Shutter Speed associated with a particular image:</p>
<pre class="perl">my $srcfile = "/home/spencerkellis/dsc0001.jpg";
my $srcfileExif = new Image::ExifTool;
my @srcfileTagList = ('ShutterSpeed');
my $srcfileInfo = $srcfileExif-&gt;ImageInfo($srcfile,@srcfileTagList);
print "Shutterspeed: ".$$srcfileInfo{'ShutterSpeed'};</pre>
<p>The code is straightforward enough; line 1 establishes a file (note the absolute path); line 2 instantiates an Image::ExifTool object; line 3 specifies which tags to read; line 4 actually reads the information; finally, line 5 prints the returned value.</p>
<h2>A Simple Example: Renaming Files Based on EXIF Date and Time</h2>
<p>One of my principle uses of perl and exiftool is to rename files automatically to a unique filename based on date and time, in the following format:</p>
<pre class="perl">YYYYMMDD-HHMMSS-II.FFF</pre>
<p>&#8216;I&#8217; stands for an &#8220;index&#8221;, to allow for cases in which multiple pictures were taken in the same second.  &#8216;F&#8217; represents the file format extension (i.e., JPG or NEF for Nikon RAW files).  The process of renaming files, tedious by hand, is simple and efficient to automate with perl.</p>
<pre class="perl">#!/usr/bin/perl -w
use File::Spec;
use Image::ExifTool;

my $p = shift;

#extract date from EXIF
my @ioTagList = ('DateTimeOriginal');
my $exifTool = new Image::ExifTool;
$exifTool-&gt;Options(DateFormat =&gt; "%Y%m%d-%H%M%S-");
my $info = $exifTool-&gt;ImageInfo($p, @ioTagList);

#create new filename
my $name = sprintf("%s00",$$info{'DateTimeOriginal'});
my ($pathvol,$pathdir,$pathfile) = File::Spec-&gt;splitpath($p);
my $newfile = File::Spec-&gt;catfile($pathvol,$pathdir,$date.".JPG");

#write files
if( -f $newfile )
{
print "skipping $p: already exists at $newfilen";
return;
}
if($p ne $newfile)
{
rename($p,$newfile) or die "Error: could not copy $p to $newfile: $!n";
}</pre>
<p>Again, a straightforward example with a few extra lines to take note of.  In this case,to simplify my perl code, I used an exiftool construct allowing options to be set which govern output format:</p>
<pre class="perl">$exifTool-&gt;Options(DateFormat =&gt; "%Y%m%d-%H%M%S-");</pre>
<p>This option instructs exiftool to output the date in a specific format corresponding to the filename format I described above.  As a simple example, I did not include my method for handling multiple files with the same date and time; the code will simply skip renaming files where the target filename already exists.  The sprintf line constructs the string holding the filename, and the File::Spec package is used to split apart and reconstruct paths.  The code requires an argument (the path to a file); in my full script, this code is a sub, and passed the filename for each entry in a directory.</p>
<h2>Command Line Alternative</h2>
<p>After spending quite a lot of time getting to know the exiftool package in perl, I started to think about ways to do it with simpler code.  As it turns out, using the command line version of exiftool can result in much cleaner code.  Consider the following, which is virtually the same perlscript as above, except executing the <span class="inline">exiftool</span> executable instead of in line perl code:</p>
<pre class="perl">my $p = shift;

#extract date from EXIF
my $date = `exiftool -d %Y%m%d-%H%M%S- -DateTimeOriginal -S -s $p`;
chomp $date;
$date .= "00";
my ($pathvol,$pathdir,$pathfile) = File::Spec-&gt;splitpath($p);
my $newfile = File::Spec-&gt;catfile($pathvol,$pathdir,$date.".JPG");

#write files
if( -f $newfile )
{
print "skipping $p: already exists at $newfilen";
return;
}
if($p ne $newfile)
{
rename($p,$newfile) or die "Error: could not copy $p to $newfile: $!n";
}</pre>
<p>Notice that the entire chunk of code instantiating the exiftool object, etc. has beenreplaced by one line calling the executable in backticks.  I haven&#8217;t done any testing to analyze which is more efficient, but it does look better, and it&#8217;s easier to conceptualize.</p>
<p><span style="color: #ff0000;"><strong>EDIT 3 Sept 2009: Updated Command Line Alternative</strong></span></p>
<p>Thanks so much to Phil Harvey, the author of ExifTool, for reading and commenting on this article.  He suggested a much cleaner command-line alternative so disregard the perlscript above! <img src='http://blog.spencerkellis.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre name="code" class="bash">
exiftool -d %Y%m%d-%H%M%S-%%.2c.%%e &quot;-FileName&lt;DateTimeOriginal&quot; FILE
</pre>
<h2>Writing Data</h2>
<p>Let&#8217;s pose an issue based on a problem I faced some time back.  Consider an automated process that copies NEF files into a source directory (all uniquely renamed), and creates a smaller JPG file specifically sized for the web (about 600&#215;400).  The process of copying and resizing, however, does not preserve the EXIF data, and I would like to restore the information for possible inclusion into my website&#8217;s database.</p>
<p>In order to do this, we need (1) the original EXIF information from the NEF source file; and (2) the ability to write or copy that EXIF data into the destination JPG file.  The following perl accomplishes this task.  The code below uses an image in the form of a &#8220;blob,&#8221; in this case what has been returned from the ImageMagick function &#8220;ImageToBlob()&#8221; which will be discussed in a different article soon.</p>
<pre class="perl">#!/usr/bin/perl -w
use Image::ExifTool;
use Image::Magick;

$srcfile = "/home/spencerkellis/20051008-133601-00.nef";

#webfile should not exist yet!
$webfile = "/home/spencerkellis/20051008-133601-00.jpg";

#process image as needed
my $IM = Image::Magick-&gt;new(magick=&gt;'jpg');
$IM-&gt;Read($srcfile);

# ... resize here ... #

#create blob
my $final_blob = $IM-&gt;ImageToBlob();

#copy exif
my $exifTool = new Image::ExifTool;
$exifTool-&gt;SetNewValuesFromFile($srcfile);
$exifTool-&gt;WriteInfo($final_blob,$webfile);</pre>
<p>All of the Image::Magick section will be discussed in a different article.  Basically, it&#8217;s a package to perform image manipulation in perl (and other languages) the same as if you had opened the image in GIMP or PhotoShop.  The last two lines are where the magic happens; after instantiating the exiftool object, the second-to-last line retrieves the EXIF data from the NEF source file, and the last line creates a new file using the image information in $final_blob (the backslash preceding the variable creates a reference to the variable) and the EXIF data already stored in the $exifTool object.  $webfile now has the same EXIF data as $srcfile!</p>
<h2>Extracting Basic JPG from NEF</h2>
<p>Accounting for about 700KB of a NEF&#8217;s size (usually around 5MB) is a full-sized Basic JPG file.  Incorporating the ability to extract this file into an automated post-processing phase means never shooting RAW+JPG, which further means more space on a compact flash card!  Not to mention potential space savings on a hard drive, and potential nightmares keeping track of which files have both NEF and JPG vs. NEF only or JPG only, vs. what has been edited for print or for web&#8230; the list goes on, and it&#8217;s a battle every digital photographer tackles at some point.</p>
<p>Using Perl and ExifTool, I wrote a script which will extract these basic JPGs automatically. The following code is incorporated into a larger script, but it shows the basic idea.  I also want to note that there are simpler ways of running batch jobs to get JPGs out of NEF files; for instance, Ihave used and enjoyed Udi Fuch&#8217;s <a href="http://ufraw.sourceforge.net/" target="_blank">UFRaw</a> package on the command-line in batch mode, and it runs fairly quickly with pretty good output.</p>
<pre class="perl">#!/usr/bin/perl -w
use Image::Magick;
use Image::ExifTool;

my $srcfile = "/home/spencerkellis/dsc0001.nef";
my $webfile = "/home/spencerkellis/dsc0001.jpg";
my @ioTagList = ('JpgFromRaw');
my $exifTool = new Image::ExifTool;
$exifTool-&gt;Options(Binary=&gt;1);
my $info = $exifTool-&gt;ImageInfo($srcfile, @ioTagList);

#manipulation
$IM = Image::Magick-&gt;new(magick=&gt;'jpg');
$IM-&gt;BlobToImage(${$$info{'JpgFromRaw'}});

# ... do manipulation here ... #

$final_blob = $IM-&gt;ImageToBlob();

#restore exif
$exifTool-&gt;SetNewValuesFromFile($srcfile);
$exifTool-&gt;WriteInfo($final_blob,$webfile);
undef $IM;
undef $final_blob;</pre>
<p>There are a few things to note here. First, in order to extract binary data (i.e., a JPG image), we have to set the Binary option in the ExifTool object to &#8217;1&#8242; (verses default 0&#8242;).  Since in my script I&#8217;m manipulating the image using the ImageMagick package, I instantiate the extracted JPG as a new ImageMagick object, do some manipulation, then export it as a blob.  Then, since EXIF data has not been preserved, I restore it using ExifTool.  The extracted JPG is finally written using ExifTool to the path specified as $webfile.</p>
<p>P.S. This article is a transfer of most of the content of an article on my old website.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.spencerkellis.net/2009/09/using-perl-and-exiftool-to-access-exif-data-in-digital-images/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Merging Google Syntax Highlighter with TinyMCE</title>
		<link>http://blog.spencerkellis.net/2009/09/merging-google-syntax-highlighter-with-tinymce/</link>
		<comments>http://blog.spencerkellis.net/2009/09/merging-google-syntax-highlighter-with-tinymce/#comments</comments>
		<pubDate>Thu, 03 Sep 2009 01:42:16 +0000</pubDate>
		<dc:creator>Spencer</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[Syntax Highlighter]]></category>
		<category><![CDATA[TinyMCE]]></category>

		<guid isPermaLink="false">http://blog.spencerkellis.net/?p=350</guid>
		<description><![CDATA[Syntax Highlighting in TinyMCE TinyMCE is a powerful in-browser WYSIWYG editor. It&#8217;s used in well-known platforms such as WordPress to allow users the ability to edit blog posts right in the browser. I&#8217;ve been using TinyMCE for several years now, but until today I hadn&#8217;t found a decent solution for adding code snippets with syntax [...]]]></description>
			<content:encoded><![CDATA[<h2>Syntax Highlighting in TinyMCE</h2>
<p><a href="http://tinymce.moxiecode.com/">TinyMCE</a> is a powerful in-browser WYSIWYG editor.  It&#8217;s <a href="http://codex.wordpress.org/TinyMCE">used in well-known platforms such as WordPress</a> to allow users the ability to edit blog posts right in the browser.  I&#8217;ve been using TinyMCE for several years now, but until today I hadn&#8217;t found a decent solution for adding code snippets with syntax highlighting inside TinyMCE.</p>
<h2>Google SyntaxHighlighter</h2>
<p>Enter <a href="http://code.google.com/p/syntaxhighlighter/">Google SyntaxHighlighter</a>.  You may have noticed the signature appearance on several web-design related websites: <a href="http://nettuts.com">nettuts.com</a>, <a href="http://davidwalsh.name/">davidwalsh.name</a>, and <a href="http://scriptandstyle.com">scriptandstyle.com</a>, just to name a few.  It integrates several attractive features &ndash; decent syntax highlighting, cross-browser (all javascript/css), and the option to view plain text.</p>
<p>SyntaxHighlighter can be configured to use either &lsquo;pre&rsquo; or &lsquo;textarea&rsquo; elements (see <a href="http://code.google.com/p/syntaxhighlighter/wiki/PreAndTextarea">this discussion</a> for more details on the choice).  In either case, add two attributes to the element and you&#8217;re set:</p>
<pre class="xhtml" name="code">&lt;pre name=code class=javascript&gt;&lt;/pre&gt;</pre>
<p>Unfortunately, working with textareas in TinyMCE is awkward at best (consider &ndash; what other use could there possibly be for textareas inside a WYSIWYG editor?).  Okay, no textareas &ndash; no problem, just switch to the pre element!  Here&#8217;s where TinyMCE&#8217;s powerful featureset gets in the way: the &lsquo;name&rsquo; attribute isn&#8217;t technically supported for the pre tag, and TinyMCE will strip it from your HTML if you try and add it by viewing the code.</p>
<p>The cleanest way to get around this problem is to add an extended_valid_elements to your tinyMCE init, and include pre[name] in the element list.  TinyMCE will merge the extended_valid_elements with the default valid_elements to allow the name attribute along with already-allowed attributes.</p>
<pre class="javascript" name="code">tinyMCE.init({
mode : "textareas",
theme : "advanced",
extended_valid_elements : "pre[name]"
});</pre>
<p>Be aware that caching can make it seem like your changes aren&#8217;t making any difference!  If in doubt, clear your cache.</p>
<h2>RichGuk&#8217;s syntaxhl TinyMCE plugin</h2>
<p>There&#8217;s an easier way than editing HTML every time you want to add a code snippet.  I found a great plugin &ndash; <a href="http://github.com/RichGuk/syntaxhl/tree/master">syntaxhl by RichGuk</a> (installation instructions are included with the download). </p>
<p> By default, his plugin uses textareas but changing it to use pre tags is simple.  Edit syntaxhl/js/dialog.js and replace all instances of the textarea tag with a pre tag (there are only two instances, opening and closing tags).  The final version is shown below:</p>
<pre class="javascript:firstline[34]" name="code">f.syntaxhl_code.value = f.syntaxhl_code.value.replace(/&lt;/g,'&lt;');
f.syntaxhl_code.value = f.syntaxhl_code.value.replace(/&gt;/g,'&gt;');
textarea_output = '&lt;pre name="code" ';
textarea_output += 'class="' + f.syntaxhl_language.value + options + '" cols="50" rows="15"&gt;';
textarea_output +=  f.syntaxhl_code.value;
textarea_output += '&lt;/pre&gt; '; /* note space at the end, had a bug it was inserting twice? */
tinyMCEPopup.editor.execCommand('mceInsertContent', false, textarea_output);
tinyMCEPopup.close();</pre>
<p>You&#8217;ll need to get the newline and br options set up correctly to preserve whitespace in your code snippets.</p>
<h2>Fully Integrated Syntax Highlighting</h2>
<p>With syntaxhl integrated and working, I have single-button access to UI-level syntax highlighting.  Writing tutorials is infinitely easier with a simple solution for sharing code. If you&#8217;re interested, I found a few alternatives along the way that might be better suited to your needs:</p>
<ul>
<li><a href="http://noteslog.com/chili/">Chili</a></li>
<li><a href="http://qbnz.com/highlighter/">GeSHi</a></li>
<li><a href="http://22bits.exofire.net/browse/code/colourcode">ColourCode</a></li>
<li><a href="http://www.cagintranet.com/archive/the-definitive-guide-on-wordpress-syntax-highligher-plugins/">The Definitive Guide on WordPress Syntax Highlighter Plugins</a></li>
<li>Alternatives listed in the <a href="http://code.google.com/p/syntaxhighlighter/wiki/Alternatives">SyntaxHighlighter Wiki</a></li>
<li><a href="http://subindie.com/php/scoops-test/">vim</a></li>
</ul>
<p>I hope this article has been useful. Let me know in the comments if you have suggestions or questions!</p>
<p>P.S. This article is a transfer of most of the content of an article on my old website.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.spencerkellis.net/2009/09/merging-google-syntax-highlighter-with-tinymce/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>MATLAB Tips and Tricks</title>
		<link>http://blog.spencerkellis.net/2009/09/matlab-tips-and-tricks/</link>
		<comments>http://blog.spencerkellis.net/2009/09/matlab-tips-and-tricks/#comments</comments>
		<pubDate>Thu, 03 Sep 2009 01:32:31 +0000</pubDate>
		<dc:creator>Spencer</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[MATLAB]]></category>
		<category><![CDATA[permute]]></category>
		<category><![CDATA[squeeze]]></category>
		<category><![CDATA[vector notation]]></category>

		<guid isPermaLink="false">http://blog.spencerkellis.net/?p=335</guid>
		<description><![CDATA[Over the course of my graduate work, I&#8217;ve spent a fair amount of time with MATLAB.  These are a few small tricks I wish I had known from the beginning. Preallocation I am a believer in preallocation.  For a particular application, I read in about 13GB of data from a file into a 4-D matrix [...]]]></description>
			<content:encoded><![CDATA[<p>Over the course of my graduate work, I&#8217;ve spent a fair amount of time with MATLAB.  These are a few small tricks I wish I had known from the beginning.</p>
<h2>Preallocation</h2>
<p>I am a believer in preallocation.  For a particular application, I read in about 13GB of data from a file into a 4-D matrix (this was running on a machine with 32GB of memory).  Before preallocation, I let the process run for about 10 hours, and it still hadn&#8217;t finished.  With preallocation the process finished in about 20 minutes.  That&#8217;s an improvement of at least 3,000%!</p>
<h2>Permute</h2>
<p>The permute function can be quite handy &#8211; it can shuffle around the dimensions in a matrix with a single function call.  Consider the following matrix:</p>
<pre class="php" name="code">m_one = rand([2 5 4000]);</pre>
<p>The size of this matrix is reported as 2x5x4000 in MATLAB. Now, we can shuffle the dimensions.  Let&#8217;s make it a 4000x2x5 array:</p>
<pre class="php" name="code">m_one = permute(m_one, [3 1 2]);</pre>
<p>The permute() function takes the array to shuffle around, and the new order of dimensions.  In this case, the 3rd dimension moved to become first, 1st dimension second, and 2nd dimension last so that a 2x5x4000 matrix becomes a 4000x2x5 matrix.</p>
<h2>Vector notation</h2>
<p>Be careful, though: as handy as permute can be, it&#8217;s easy to use it inefficiently.  Remember that 13GB 4-D matrix?  I ran permute on that, and memory usage immediately doubled.  In general, I recommend creating the data the right way first!  It will save a lot of headache (and RAM) down the road.  </p>
<p>If you desperately need only a subset of dimensions, an alternative solution is to use MATLAB&#8217;s built-in, efficient vector notation.  For example, to extract the first and third dimensions for a single 2nd-dimension element, just use</p>
<pre class="php" name="code">m_two = m_one(:,1,:);  </pre>
<p>The one downside here is that you&#8217;ll end up with an annoying singleton dimension that can frustrate other builtin functions like plot.  The squeeze function will rescue us.</p>
<h2>Squeeze</h2>
<p>Squeeze is cool.  After running the previous code, size(m_two) shows us that m_two is a 4000x1x5 matrix.  We could use indexing to access all these elements, but squeeze will make life much easier &#8211; it will remove the singleton dimension in the middle.</p>
<pre class="php" name="code">m_two = squeeze(m_two);  </pre>
<p>Now, size(m_two) tells us we&#8217;ve got a 4000&#215;5 matrix and using the matrix just got that much simpler.</p>
<h2>Removing elements from vectors and matrices</h2>
<p>There are times when you want to discard elements from a vector or matrix.  I used to do this by creating a new variable to hold just the elements I wanted to keep.  Obviously, there&#8217;s a better way.  Let&#8217;s remove all the elements of a matrix that are less than 0.5.  It&#8217;s insanely easy:</p>
<pre class="php" name="code">
m_three = rand(1,1000);
m_three( m_three < 0.5 ) = [];
</pre>
<p>Now, size(m_three) gives 1x2023.</p>
<h2>Conclusions</h2>
<p>If you haven't noticed yet, MATLAB is all about the matrices.  Understanding how to efficiently operate on subsets of matrices will give you huge returns in performance.  Learn how and when to use permute, squeeze, and vector notation and you'll be well on your way.  Anything else you think should be on this page?  Let me know in the comments!</p>
<p>P.S. This article is a transfer of most of the content of an article on my old website.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.spencerkellis.net/2009/09/matlab-tips-and-tricks/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>RSSPhoto: A WordPress Widget</title>
		<link>http://blog.spencerkellis.net/2009/08/rssphoto-a-wordpress-widget/</link>
		<comments>http://blog.spencerkellis.net/2009/08/rssphoto-a-wordpress-widget/#comments</comments>
		<pubDate>Wed, 05 Aug 2009 02:22:45 +0000</pubDate>
		<dc:creator>Spencer</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[project]]></category>
		<category><![CDATA[RSSPhoto]]></category>
		<category><![CDATA[widget]]></category>
		<category><![CDATA[Wordpress]]></category>

		<guid isPermaLink="false">http://blog.spencerkellis.net/?p=277</guid>
		<description><![CDATA[I&#8217;ve made a WordPress widget called RSSPhoto that pulls images from photoblog RSS or Atom feeds and displays a thumbnail in the sidebar (I&#8217;m using it in my sidebar).  I mentioned the beginnings of this project a couple posts back.  That one was pulling images straight out of my database though.  This version is more [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve made a WordPress widget called RSSPhoto that pulls images from photoblog RSS or Atom feeds and displays a thumbnail in the sidebar (I&#8217;m using it in my sidebar).  I mentioned the beginnings of this project a couple posts back.  That one was pulling images straight out of my database though.  This version is more generic and uses the <a href="http://simplepie.org/">SimplePie</a> PHP library for parsing feeds.</p>
<p>Even though I say it pulls from photoblog feeds, really it can pull from any feed&#8211;it will just pull one of the images out of the content of a feed item.  I&#8217;ve used it to pull Flickr RSS feeds and a couple other random ones.  I also installed it easily on <a href="http://www.thesassylime.com">Emily&#8217;s blog</a>.</p>
<p>Check it out on my new Projects page (<a href="http://blog.spencerkellis.net/projects/rssphoto/">direct link</a>).  If you have a WordPress blog, try it out and let me know how your experience was.  I&#8217;d definitely appreciate any feedback.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.spencerkellis.net/2009/08/rssphoto-a-wordpress-widget/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Plugins and Widgets and WordPress&#8211;Oh my!</title>
		<link>http://blog.spencerkellis.net/2009/07/plugins-and-widgets-and-wordpress-oh-my/</link>
		<comments>http://blog.spencerkellis.net/2009/07/plugins-and-widgets-and-wordpress-oh-my/#comments</comments>
		<pubDate>Sat, 25 Jul 2009 22:21:41 +0000</pubDate>
		<dc:creator>Spencer</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[identity crisis]]></category>
		<category><![CDATA[just one line of code]]></category>
		<category><![CDATA[Photography]]></category>
		<category><![CDATA[widget]]></category>

		<guid isPermaLink="false">http://blog.spencerkellis.net/?p=228</guid>
		<description><![CDATA[From my last post you know I&#8217;m trying to figure out the best configuration of my domain and subdomains.  I&#8217;m leaning toward the blog as my principal domain content with the photography blog as a linked subdomain. To sleep well at night with this change, I need a good way to interface my photography with [...]]]></description>
			<content:encoded><![CDATA[<p>From my last post you know I&#8217;m trying to figure out the best configuration of my domain and subdomains.  I&#8217;m leaning toward the blog as my principal domain content with the photography blog as a linked subdomain.</p>
<p><img class="alignleft size-full wp-image-254" title="sidebar" src="http://blog.spencerkellis.net/wp-content/uploads/2009/07/sidebar.jpg" alt="sidebar" width="100" height="275" /></p>
<p>To sleep well at night with this change, I need a good way to interface my photography with the blog.  After testing a few options, I decided to try developing a WordPress Widget to display the most recent photo.  It was surprisingly easy!  I thought I might document a bit about the design of a WordPress widget.  I know my audience (consisting mostly of family) has <em>really </em>been hoping for a technical article with some code to sink their teeth into.  Right?</p>
<p>To really understand widgets, you should play around with them first in your own admin section, under Appearance-&gt;Widgets.  You can drag and drop from available widgets to the sidebar or footer to define the contents of those areas of your blog.  You&#8217;ll notice when you drag a widget, a form appears with some fields to define.</p>
<p>On to creating a widget.  First, make a directory to hold all the plugin files in the <code>wp-content/plugins</code> directory.  Mine, for example, is <code>wp-content/plugins/skphoto/</code>.</p>
<p>Second, you need to define a class that extends WP_Widget, and includes a constructor function, widget function, update function, and form function.  This same file should also register the widget.  Here&#8217;s an outline of what that looks like:</p>
<pre name="code" class="php">class WidgetName extends WP_Widget
{
  /* constructor */
  function WidgetName() {}

  /* display the widget */
  function widget($args, $instance) {}

  /* save widget settings */
  function update($new_instance, $old_instance) {}

  /* edit form for the widget */
  function form($instance) {}
}

function WidgetNameInit()
{
  register_widget('WidgetName');
}
add_action('widgets_init', 'WidgetNameInit');</pre>
<p>See Jesse Altman&#8217;s <a href="http://jessealtman.com/2009/06/08/tutorial-wordpress-28-widget-api/">tutorial post</a> for details on these functions.</p>
<p>I do want to give a bit more information about the widget function.  If you want to access your MySQL database from within the widget function, you&#8217;ll need to add <code>global $wpdb;</code> to the top of your function.  Then, you can use standard WordPress <a href="http://codex.wordpress.org/Function_Reference/wpdb_Class">database functions</a> to pull data out.</p>
<p>Here&#8217;s the basics of my widget function for reference:</p>
<pre name="code" class="php">  function widget($args, $instance){
    global $wpdb;
    extract($args);
    $title = apply_filters('widget_title', empty($instance['title']) ? ' ' : $instance['title']);
    $feed_url = empty($instance['feed_url']) ? 'http://photography.spencerkellis.net/atom.php' : $instance['feed_url'];

    # Before the widget
    echo $before_widget;

    # The title
    if ( $title )
    echo $before_title . $title . $after_title;

    $sql = "SELECT `path` FROM `photos` ORDER BY `date` DESC LIMIT 1";
    $path = $wpdb-&gt;get_var($sql);
    echo "<img src=".$path." alt="" />";

    # After the widget
    echo $after_widget;
  }</pre>
<p>Finally, activate your new plugin in the WordPress Plugins section.  Then go back to the Widgets where the new widget will be available to drag and drop.</p>
<p>So there it is.  Easy-peezy, right?  Just a few lines of code, as I always like to say.  Here are a few resources if you want to explore on your own:</p>
<ul>
<li><a href="http://jessealtman.com/2009/06/08/tutorial-wordpress-28-widget-api/">Jesse Altman &#8211; Widget Tutorial</a></li>
<li><a href="http://wpengineer.com/wordpress-built-a-widget/">WP Engineer &#8211; Build a Widget</a></li>
<li><a href="http://codex.wordpress.org/Writing_a_Plugin">WordPress Docs &#8211; Writing a Plugin</a></li>
<li><a href="http://codex.wordpress.org/Function_Reference/wpdb_Class">WordPress Docs &#8211; Function Reference / wpdb Class</a></li>
<li><a href="http://codex.wordpress.org/Developer_Documentation">WordPress Docs &#8211; Developer Documentation</a></li>
</ul>
<p>So I&#8217;ll be looking for your thoughts.  What do you think about this solution for a home page?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.spencerkellis.net/2009/07/plugins-and-widgets-and-wordpress-oh-my/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
