Yêu cầu trước khi bắt đầu
- Đã cài đặt localhost bằng XAMPP
- Có kiến thức PHP căn bản
1. Tạo thư mục làm việc
Trong thư mục htdocs, bạn tạo một thư mục mới tên là resize với cấu trúc sau:
resize/
├── dir/ # thư mục chứa hình gốc
├── exp/ # thư mục xuất hình đã xử lý
├── index.php
2. Code PHP xử lý resize + crop căn giữa
Sao chép đoạn mã sau vào tập tin index.php:
<?php
function resize_crop_image($max_width, $max_height, $source_file, $dst_dir, $quality = 80) {
$imgsize = getimagesize($source_file);
if (!$imgsize) return false;
$width = $imgsize[0];
$height = $imgsize[1];
$mime = $imgsize['mime'];
switch ($mime) {
case 'image/gif':
$image_create = 'imagecreatefromgif';
$image_output = 'imagegif';
break;
case 'image/png':
$image_create = 'imagecreatefrompng';
$image_output = 'imagepng';
$quality = 7;
break;
case 'image/jpeg':
$image_create = 'imagecreatefromjpeg';
$image_output = 'imagejpeg';
$quality = 80;
break;
default:
return false;
}
if (!function_exists($image_create)) return false;
$dst_img = imagecreatetruecolor($max_width, $max_height);
$src_img = $image_create($source_file);
if ($mime === 'image/png') {
imagealphablending($dst_img, false);
imagesavealpha($dst_img, true);
}
$width_new = $height * $max_width / $max_height;
$height_new = $width * $max_height / $max_width;
if ($width_new > $width) {
$h_point = ($height - $height_new) / 2;
imagecopyresampled($dst_img, $src_img, 0, 0, 0, $h_point, $max_width, $max_height, $width, $height_new);
} else {
$w_point = ($width - $width_new) / 2;
imagecopyresampled($dst_img, $src_img, 0, 0, $w_point, 0, $max_width, $max_height, $width_new, $height);
}
$image_output($dst_img, $dst_dir, $quality);
imagedestroy($dst_img);
imagedestroy($src_img);
}
// Duyệt tất cả ảnh trong thư mục ./dir và xử lý
$sourceDir = './dir/';
$destDir = './exp/';
$files = scandir($sourceDir);
foreach ($files as $file) {
$source = $sourceDir . $file;
$target = $destDir . $file;
if (is_file($source)) {
resize_crop_image(450, 400, $source, $target, 80);
}
}
echo 'ok';
?>
3. Hướng dẫn sử dụng
- Chép tất cả hình ảnh gốc vào thư mục
resize/dir/ - Mở trình duyệt và truy cập
http://localhost/resize/ - Các hình đã được resize + crop sẽ được xuất ra thư mục
resize/exp/
Lưu ý thêm
- Hàm tự nhận diện định dạng ảnh (JPG, PNG, GIF) và xử lý phù hợp
- Đối với PNG, ảnh sẽ giữ được nền trong suốt
- Bạn có thể thay đổi kích thước đầu ra bằng cách chỉnh thông số
450x400trong hàm
Kết luận
Đây là một thủ thuật đơn giản nhưng rất hữu dụng để xử lý hàng loạt ảnh trong các dự án web cần đồng nhất kích thước hiển thị. Bạn có thể tích hợp đoạn code này vào các tool upload nội bộ, hoặc phát triển thêm giao diện để chọn size, preview, hoặc xử lý nâng cao hơn nếu cần.
Bình luận