Skip to content

Instantly share code, notes, and snippets.

@mlopes
Created February 17, 2012 10:36
Show Gist options
  • Save mlopes/1852550 to your computer and use it in GitHub Desktop.
Save mlopes/1852550 to your computer and use it in GitHub Desktop.
Convert wordpress style caption tags to octopress image tags
#!/usr/bin/perl
use strict;
my $script_name = $ARGV[0];
my $file_contents = "";
while(<>) {
if($_ =~ /\[caption.*/) {
my %imageData;
my $line = $_;
# url
my $url;
if($line =~ /\(http.*\/(\d\d\d\d)\/(\d\d)\/(.*)\)\[/){
$url = $imageData{'img'} = $script_name . "/" . $3;
$url =~ s/\.markdown//g
}
my $imgInfo;
# Get image information - Comment this one out if you don't have ImageMagick
$imgInfo = `identify ../images/posts/$url`;
# width
if($line =~ /width=\"(\d+)\"/){
$imageData{'width'} = $1;
} else {
if($imgInfo =~ /\s+(\d+)x\d+\s+/) {
$imageData{'width'} = $1;
}
}
# height
if($line =~ /height=\"(\d+)\"/){
$imageData{'height'} = $1;
} else {
if($imgInfo =~ /\s+\d+x(\d+)\s+/) {
$imageData{'height'} = $1;
}
}
# align
if($line =~ /align=\"align(\w+)\"/){
$1 = 'center' if($1 eq 'none');
$imageData{'align'} = $1;
}
# caption
if($line =~ /caption=\"(.+)\"/){
$imageData{'caption'} = $1;
}
$file_contents .= '{% img ';
$file_contents .= ' ' . $imageData{'align'} . ' ';
$file_contents .= '/images/posts/' . $imageData{'img'}. ' ';
if(!$imageData{'width'}) {
$file_contents .= ' %}' . "\n";
next;
}
$file_contents .= ' ' . $imageData{'width'} . ' ';
if(!$imageData{'height'}) {
$file_contents .= ' %}' . "\n";
next;
}
$file_contents .= ' ' . $imageData{'height'} . ' ';
if(!$imageData{'caption'}) {
$file_contents .= ' %}' . "\n";
next;
}
$file_contents .= '"' . $imageData{'caption'} . '" "' . $imageData{'caption'} . '" ' if($imageData{'caption'});
$file_contents .= ' %}' . "\n";
} else {
$file_contents .= $_;
}
}
open FILE, ">" . $script_name;
print FILE $file_contents;
close FILE;
@mlopes
Copy link
Author

mlopes commented Feb 17, 2012

Line 23 uses ImageMagick's identify utility to find information about the image and fill any holes it finds on the information provided by the caption tag.

The script assumes images are on your source/images/posts/ folder.

The images on source/images/posts/ are as provided by running exitwp on the origin wordpress blog.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment