如何用PHP制作缩略图

aka*_*no1 2 php

我只是想知道如何制作存储在硬盘中的图像的缩略图并在html页面中使用它们,我还需要缩略图才能放大(到原来的大小),如果点击最好在同一页面上的div标签内如果有人能把我放在正确的方向,我将不胜感激

谢谢

Pau*_*sma 5

您需要启用GD扩展.以下代码将在一个名为~tmbJPEG,PNG和GIF文件的子目录中创建一个缩略图文件:

$invalid = true;
if ($file != '.' and $file != '..') {
    if (filetype($path_abs.$file) == "file") {
        $ext = strtolower(substr($file,strrpos($file,'.')+1));
        if ($ext == 'jpg' || $ext == 'jpeg') {
            $origimg = @imagecreatefromjpeg($path_abs.$file);
        } elseif ($ext == 'png') {
            $origimg = @imagecreatefrompng($path_abs.$file);
        } elseif ($ext == 'gif') {
            $origimg = @imagecreatefromgif($path_abs.$file);
        }
        if ($origimg !== false) {
            $nheight = 0;
            $nwidth = 0;
            $use_orig = false;
            if ($width<=160 and $height<160) {
                $nwidth = $width;
                $nheight = $height;
                $use_orig = true;
                $invalid = false;
            } else {
                if ($width>$height and $width>0) {
                    $nheight = intval((160 / $width) * $height);
                    $nwidth = 160;
                } elseif ($height>0) {
                    $nwidth = intval((160 / $height) * $width);
                    $nheight = 160;
                } else {
                    $image = false;
                }
                if ($nheight > 0 and $nwidth > 0) {
                    $newimg = imagecreatetruecolor($nwidth, $nheight);
                    $bgc = imagecolorallocate ($newimg, 238, 238, 238);
                    imagefilledrectangle ($newimg, 0, 0, $nwidth, $nheight, $bgc);
                    if (@imagecopyresampled($newimg, $origimg, 0, 0, 0, 0, $nwidth, $nheight, $width, $height)) {
                        $image = imagejpeg($newimg, $path_abs.'~tmb/'.$file);
                        $invalid = false;
                    } elseif (@imagecopyresized($newimg, $origimg, 0, 0, 0, 0, $nwidth, $nheight, $width, $height)) {
                        $image = imagejpeg($newimg, $path_abs.'~tmb/'.$file);
                        $invalid = false;
                    }
                }
            }
        }
    }
}
if (!$invalid) {
    if ($use_orig) {
        echo '<img src="'.$file.'" alt="" />';
    } else {
        echo '<img src="~tmb/'.$file.'" alt="" />';
    }
} else {
    echo '<p>Error for file '.$file.'</p>';
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,它将它们的大小调整为160x160,但保持纵横比.