This will create PNG files for all of the UPCA UPCs that are stored in a database. This is a quick hack (maybe five minutes of coding) and in no way finished software. Next I will store the generated PNG file in the database as well.
I've left some commented code in place for reference.
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
use GD::Barcode;
my $db = "database";
my $db_engine = "mysql";
my $host = "localhost";
my $user = "username";
my $password = "password";
my $dbh = DBI->connect("DBI:$db_engine:$db:$host",$user, $password,{ P
+rintError => 0}) || die $DBI::errstr;
GetUPCs($dbh);
my $rc = $dbh->disconnect;
exit;
sub GetUPCs {
my $dbh = shift;
my $table = "items";
#my $select = "item_id, status, description, upc"; my $select =
+ "upc"; # get whatever info you store on the item
my $sth;
# The length check is for our specific setup.
# Our accounting software cannot handle UPCs with more than 10 digits.
+ (Go figure)
# Someone here has stored some with only 4 and others with 5 digits.
+(Waiting on confirmation? Dunno)
# However, I have stored some in the database with 11 digits.
$sth = $dbh->prepare("SELECT $select FROM $table WHERE upc <> '' A
+ND length(upc) >= 10 ;");
if (!$sth) {
die "Error:" . $dbh->errstr . "\n";
}
if (!$sth->execute) {
die "Error:" . $sth->errstr . "\n";
}
my $row_ref;
while($row_ref = $sth->fetchrow_arrayref) {
#print "Item #: $row_ref->[0]\n";
#print "Status: $row_ref->[1]\n";
#print "Description: $row_ref->[2]\n";
#print "UPC: $row_ref->[3]\n";
print "UPC: $row_ref->[0]\n";
print "\n";
#CreateBarCodes('UPCA', $row_ref->[3]);
CreateBarCodes('UPCA', $row_ref->[0]);
}
my $rv = $sth->finish;
}
sub CreateBarCodes {
my ($type, $upc) = @_;
my $oGdBar;
my $sPtr;
$upc = "0".$upc if (length($upc) == 10); # if < 11 digits,
+add a 0 to the front
chop $upc if (length($upc) == 12); # if > 11 digits, remove the
+ check digit
$oGdBar = GD::Barcode->new($type, $upc);
die $GD::Barcode::errStr unless($oGdBar); #Invalid Length
open(IMG, ">./png/$upc.png") or die $!;
binmode(IMG);
print IMG $oGdBar->plot->png;
close(IMG);
#open(IMG, ">./png/small/$upc.png") or die $!;
#binmode(IMG);
#print IMG $oGdBar->plot(NoText=>1, Height => 20)->png;
#close(IMG); *** Thanks jeffa for pointing out my missing '#' ***
}