Site icon Init HTML

Resize và Crop căn giữa hàng loạt hình ảnh với PHP

Để thực hành bài viết này, các bạn cần:

Đầu tiên, bạn tạo thư mục resize trong htdocs như sau:

resize/
├── dir/
├── exp/
├── index.php

Tại tập tin index.php.

<?php
	function resize_crop_image ($max_width, $max_height, $source_file, $dst_dir, $quality = 80) {
		$imgsize = getimagesize($source_file);
		$width = $imgsize[0];
		$height = $imgsize[1];
		$mime = $imgsize['mime'];
	 
		switch ($mime) {
			case 'image/gif':
				$image_create = "imagecreatefromgif";
				$image = "imagegif";
				break;
			case 'image/png':
				$image_create = "imagecreatefrompng";
				$image = "imagepng";
				$quality = 7;
				break;
			case 'image/jpeg':
				$image_create = "imagecreatefromjpeg";
				$image = "imagejpeg";
				$quality = 80;
				break;
			default:
				return false;
				break;
		}
		 
		$dst_img = imagecreatetruecolor($max_width, $max_height);
		$src_img = $image_create($source_file);
		 
		$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 ($dst_img, $dst_dir, $quality);
	 
		if ($dst_img) imagedestroy($dst_img);
		if ($src_img) imagedestroy($src_img);
	}

	$files = scandir('./dir');
	if ($files) {
		for ($i = 2; $i < count($files); $i++) {
			$filePath = './dir/' . $files[$i];
			$expPath = './exp/' . $files[$i];
			resize_crop_image(450, 400, $filePath, $expPath, 80);
		}
	}
	
	echo 'ok';
?>

Ví dụ trên sẽ cắt hình theo kích thước 450x400, với chất lượng ảnh lưu là 80%. Các bạn có thể thay đổi thông số này theo nhu cầu.

Để sử dụng, các bạn chép hình vào thư mục dir, sau đó truy cập http://localhost/resize/. Hình đã xử lý sẽ được xuất sang thư mục exp.

Chúc các bạn thành công!

Exit mobile version