php上传图片生成缩略图(GD库)

这篇文章主要介绍了php上传图片生成缩略图,还阐述了利用GD库上传图片以及创建缩略图,感兴趣的小伙伴们可以参考一下。

首先来一段简单的php上传图片生成缩略图的详细代码,分享给大家供大家参考,具体内容如下:

  1. <?php
  2. function createThumbnail($imageDirectory, $imageName, $thumbDirectory, $thumbWidth, $quality){
  3. $details = getimagesize("$imageDirectory/$imageName") or die('Please only upload images.');
  4. $type = preg_replace('@^.+(?<=/)(.+)$@', '$1', $details['mime']);
  5. eval('$srcImg = imagecreatefrom'.$type.'("$imageDirectory/$imageName");');
  6. $thumbHeight = $details[1] * ($thumbWidth / $details[0]);
  7. $thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
  8. imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight,
  9. $details[0], $details[1]);
  10. eval('image'.$type.'($thumbImg, "$thumbDirectory/$imageName"'.
  11. (($type=='jpeg')?', $quality':'').');');
  12. imagedestroy($srcImg);
  13. imagedestroy($thumbImg);
  14. }
  15. foreach ($_FILES["pictures"]["error"] as $key => $error) {
  16. if ($error == UPLOAD_ERR_OK) {
  17. $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
  18. $name = $_FILES["pictures"]["name"][$key];
  19. move_uploaded_file($tmp_name, "data/$name");
  20. createThumbnail("/location/of/main/image", $name, "/location/to/store/thumb", 120, 80);
  21. //120 = thumb width :: 80 = thumb quality (1-100)
  22. }
  23. }
  24. ?>

接下来再为大家推荐一个实例php使用GD库上传图片以及创建缩略图,直接看代码:

GD库是PHP进行图象操作一个很强大的库。

先在php.ini里增加一行引用:extension=php_gd2.dll

重启apache,做一个测试页var_dump(gd_info());输出数据表明GD库引用成功。

图片上传页面 upload.html

  1. <html>
  2. <head>
  3. <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
  4. <title>图片上传</title>
  5. </head>
  6. <body>
  7. <h1>文件上传(只允许上传jpg类型图片)</h1>
  8. <form enctype="multipart/form-data" action="upload_img.php" method="post">
  9. <input name="upfile" type="file"><br><br>
  10. <input type="submit" value="提交">
  11. </form>
  12. </body>
  13. </html>

处理页面upload_img.php

  1. <?php
  2. //上传图片保存地址
  3. $uploadfile = "upfiles/".$_FILES['upfile']['name'];
  4. //缩略图保存地址
  5. $smallfile = "upfiles/small_".$_FILES['upfile']['name'];
  6. if($_FILES['upfile']['type'] != "image/jpeg")
  7. {
  8. echo '文件类型错误';
  9. }
  10. else
  11. {
  12. move_uploaded_file($_FILES['upfile']['tmp_name'],$uploadfile); //上传文件
  13. $dstW=200;//缩略图宽
  14. $dstH=200;//缩略图高
  15. $src_image=ImageCreateFromJPEG($uploadfile);
  16. $srcW=ImageSX($src_image); //获得图片宽
  17. $srcH=ImageSY($src_image); //获得图片高
  18. $dst_image=ImageCreateTrueColor($dstW,$dstH);
  19. ImageCopyResized($dst_image,$src_image,0,0,0,0,$dstW,$dstH,$srcW,$srcH);
  20. ImageJpeg($dst_image,$smallfile);
  21. echo '文件上传成功<br>';
  22. echo "<img src='$smallfile' />";
  23. }
  24. ?>