我正在构建缩略图系统,但我的代码会输出一堆或随机图标。它显然应该有效,但它没有。
代码:
<?php
// The file
$filename = 'post/imgres/posts/1.jpg';
// Set a maximum height and width
$width = 200;
$height = 200;
// Content type
header('Content-Type: image/jepg');
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output
imagejpeg($image_p, null, 100);
?>
答案 0 :(得分:0)
我在claviska找到了一个叫做simpleimage的课程。我的代码现在完成了。这一切看起来都像这样。
处理缩略图的代码:
function isThumb($thumbnail)
{
if (file_exists($thumbnail))
{
return true;
}
return false;
}
function makeThumb($original, $destination)
{
$img = new abeautifulsite\SimpleImage($original);
$img->fit_to_width(256);
$img->save($destination);
}
?>
加载图片的代码:
<?php
//Image loader
//Folder containing images.
$filedir = "imgres/posts/";
//Retrieve the images in the folder.
$images = glob($filedir."*.{jpg,JPG,png,PNG,gif,GIF}",GLOB_BRACE);
//Make sure the image array is not empty, or null.
if (!empty($images))
{
//Load the images into the website.
foreach ($images as $image)
{
if (pathinfo($image,PATINFO_EXTENSION) == "gif" || pathinfo($image, PATHINFO_EXTENSION)=="GIF")
{
echo '<a href="'.$image.'"><img src="'.$image.'"/></a>';
}
else
{
echo '<a href="'.$image.'"><img src="'.getThumb($image).'"/></a>';
}
}
}
else
{
//Write out an error message to warn the user.
echo "<p>No images were found in the server. This is most likely an error in the PHP code, incompatibility, or something went wrong with our storage solution. Contact admin! Information needed: Browser, OS, and has the site worked before?</p>";
}
?>
答案 1 :(得分:0)
PHP图像缩略图是一项常见的任务,并且有大量实体图像缩略图示例和源代码。我不确定你的脚本在做什么,但这里是一个准确的基本脚本,它始终有效且直接。
您应该涵盖并支持所有图片类型png和gif&#39。但是既然你正在做jpeg,那就让我们现在用它。添加对其他图像类型的支持不应该那么困难。
/* read the source image */
$source_image = imagecreatefromjpeg($src);
$width = imagesx($source_image);
$height = imagesy($source_image);
/* find the "desired height" of this thumbnail, relative to the desired width */
$desired_height = floor($height * ($desired_width / $width));
/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
/* copy source image at a resized size */
imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
// Content type, you need this line of code to
// display image to browser or for testing it on the UI
header('Content-Type: image/jepg');
/* create the physical thumbnail image to its destination */
imagejpeg($virtual_image, $dest);