PHP : การโชว์ thumbnail

ไฟล์ภาพขนาดเล็ก (Thumbnail) เก็บอยู่ที่ “./thumbnail/”
ส่วนภาพขนาดใหญ่เก็บอยู่ที่ “./uploads/”
ดังนั้นเวลาแสดงภาพให้นำภาพที่ “./thumbnail/” มาแสดง แต่เวลาสร้างลิงค์ไปที่ไฟล์รูปภาพขนาดใหญ่ให้ชี้ไปที่ “./uploads/”

[code lang=”php”]
<?
$imgPathUpload = "./uploads/";
$imgPathThumbnail = "./thumbnail/";
$dirHandle = opendir($imgPathThumbnail);
while ($file = readdir($dirHandle)) {
if(!is_dir($file) && strpos($file, ‘.jpg’)>0 || strpos($file, ‘.gif’)>0 || strpos($file, ‘.png’)>0) {
if (strpos($file,"thumb_")===FALSE)
echo ("<a href=$imgPathUpload$file><img src=$imgPathThumbnail$file></a>");
}
}
closedir($dirHandle);
?>
[/code]

PHP: แสดง thumbnail ของภาพแรกใน Post

นำภาพแรกใน post (ในที่นี้สมมุติข้อความใน post ไว้ใน $post ในบรรทัดที่ 10) มาแสดง (บรรทัดที่ 22)
[code lang=”php”]
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8">
<title>ทดสอบ Create thumbnail</title>
</head>
<body>
<?php
function catch_that_image() {
$post = ‘some text with two pictures: <img src="http://www.example.com/image1.jpg" /> <img src="http://www.example.com/image2.png" />’;
$first_img = ”;
$output = preg_match_all(‘/<img.+src=[\’"]([^\’"]+)[\’"].*>/i’, $post, $matches);
$first_img = $matches[1][0];
/*$second_img = $matches[1][1];*/

if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}
?>
<p><img src="<?php echo catch_that_image() ?>" width="110"></p>
</body>
</html>
[/code]

ดัดแปลงโค๊ดมาจาก http://www.wprecipes.com, http://css-tricks.com