You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于CentOS7 Minimal的Perl脚本开发:从数据库取图像象限并裁剪

Hey there! Let's build those two Perl scripts you're asking for, step by step. I'll include practical code examples and explanations tailored to your exact requirements.

Script 1: Image Upload, Cropping & Sharpening with ImageMagick

This script handles web-based file uploads (using Perl's CGI module) and leverages ImageMagick's convert command to crop images and apply sharpening for clarity.

Key Requirements & Dependencies

  • ImageMagick: Verify it's installed with convert --version; on CentOS 7, install via yum install ImageMagick.
  • Perl CGI Module: Pre-installed with most Perl distributions, but if missing, grab it with yum install perl-CGI.

Full Script Implementation

#!/usr/bin/perl
use strict;
use warnings;
use CGI;
use CGI::Carp qw(fatalsToBrowser); # For easy debugging in web contexts

# Initialize CGI handler
my $cgi = CGI->new;

# Handle file upload input
my $upload_file = $cgi->upload('image_upload');
if (!$upload_file) {
    print $cgi->header('text/plain');
    print "Error: No file was uploaded!";
    exit;
}

# Define paths and processing parameters
my $temp_upload = "/tmp/uploaded_temp.jpg";
my $cropped_path = "/var/www/cropped_result.jpg"; # Adjust to your target directory
my $sharpened_path = "/var/www/sharpened_result.jpg";
my $crop_spec = "800x600+50+50"; # Format: WxH+X+Y (width, height, x-offset, y-offset)

# Save uploaded file to temp location
open my $out_fh, '>', $temp_upload or die "Failed to create temp file: $!";
binmode $out_fh;
while (my $chunk = <$upload_file>) {
    print $out_fh $chunk;
}
close $out_fh;

# Step 1: Crop the image
my $crop_cmd = "convert $temp_upload -crop $crop_spec $cropped_path";
system($crop_cmd) == 0 or die "Crop command failed: $?";

# Step 2: Apply sharpening to the cropped image
my $sharpen_cmd = "convert $cropped_path -sharpen 0x1.2 $sharpened_path";
system($sharpen_cmd) == 0 or die "Sharpen command failed: $?";

# Clean up temp file
unlink $temp_upload;

# Output success message
print $cgi->header('text/plain');
print "Image processed successfully! Check outputs at:\n$cropped_path\n$sharpened_path";

Quick Notes

  • Tweak $crop_spec to match your desired crop area (replace 800x600+50+50 with your values).
  • Ensure target directories have write permissions for the script's running user.
  • For local file processing (not web uploads), skip the CGI logic and directly pass a local file path instead.

Script 2: Image Cropping Using Database Quadrant Data (CentOS 7 Minimal)

This script connects to a database to fetch quadrant coordinates, then uses ImageMagick to crop images based on those values and save the new files. Perfect for batch processing based on stored data.

Key Requirements & Dependencies

  • ImageMagick: Install via yum install ImageMagick on CentOS 7 Minimal.
  • Perl DBI & Database Driver: For database connectivity (e.g., for MySQL/MariaDB, install with yum install perl-DBI perl-DBD-MySQL).
  • Database Table: Ensure you have a table storing quadrant data (e.g., image_quadrants with columns: source_path, output_path, x_offset, y_offset, width, height).

Full Script Implementation

#!/usr/bin/perl
use strict;
use warnings;
use DBI;

# Database connection details (update these to match your setup)
my $db_host = 'localhost';
my $db_name = 'your_database';
my $db_user = 'your_db_user';
my $db_pass = 'your_db_password';

# Connect to the database
my $dbh = DBI->connect(
    "DBI:mysql:database=$db_name;host=$db_host",
    $db_user,
    $db_pass,
    { RaiseError => 1, AutoCommit => 1 }
) or die "Database connection failed: " . DBI->errstr;

# Fetch unprocessed image quadrant data
my $query = qq{
    SELECT source_path, output_path, x_offset, y_offset, width, height
    FROM image_quadrants
    WHERE processed = 0
};
my $sth = $dbh->prepare($query);
$sth->execute();

# Process each image record
while (my $row = $sth->fetchrow_hashref) {
    my ($source, $output, $x, $y, $w, $h) = (
        $row->{source_path},
        $row->{output_path},
        $row->{x_offset},
        $row->{y_offset},
        $row->{width},
        $row->{height}
    );

    # Skip if source file doesn't exist
    unless (-f $source) {
        warn "Source file missing: $source. Skipping...";
        next;
    }

    # Build and run the ImageMagick crop command
    my $crop_cmd = "convert $source -crop ${w}x${h}+${x}+${y} $output";
    my $exit_status = system($crop_cmd);

    if ($exit_status == 0) {
        print "Successfully cropped: $source -> $output\n";
        # Optional: Mark the record as processed in the database
        $dbh->do(
            qq{UPDATE image_quadrants SET processed = 1 WHERE source_path = ?},
            undef,
            $source
        );
    } else {
        warn "Crop failed for $source. Exit status: $exit_status";
    }
}

# Clean up database connections
$sth->finish();
$dbh->disconnect();

print "All image processing tasks completed!\n";

Quick Notes

  • Update the database connection parameters to match your server's setup.
  • Adjust the SQL query to fit your table's schema (add filters or columns as needed).
  • On CentOS 7 Minimal, ensure your database service is running (e.g., systemctl start mariadb for MySQL/MariaDB).

内容的提问来源于stack exchange,提问作者Saqib Akhtar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:32:01