php - 使用 php 和 mysql 上传图像并调整大小而不变形图像

标签 php html mysql css image

我有上传图片并将其存储在数据库中的代码,但我需要在上传时调整图片大小而不使其变形。我尽量不使用 js,但如果需要,请使用并帮助我。

这是我的文件add_post.php:

<?php //include config
require_once('../includes/config.php');

//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: ../login.php'); }
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Admin - Add Post</title>
  <link rel="stylesheet" href="../style/normalize.css">
  <link rel="stylesheet" href=".style/style.css">
  <script src="//tinymce.cachefly.net/4.0/tinymce.min.js"></script>
  <script>
          tinymce.init({
              selector: "textarea",
              plugins: [
                  "advlist autolink lists link image charmap print preview anchor",
                  "searchreplace visualblocks code fullscreen",
                  "insertdatetime media table contextmenu paste"
              ],
              toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image"
          });
  </script>
</head>
<body>
    <?php include('template/menu.php');?>
<div id="wrapper">

    <p><a href="./">Blog Admin Index</a></p>

    <h2>Add Post</h2>

    <?php

    //if form has been submitted process it
    if(isset($_POST['submit'])){

        $_POST = array_map( 'stripslashes', $_POST );

        $file = rand(1000,100000)."-".$_FILES['file']['name'];
        $file_loc = $_FILES['file']['tmp_name'];
        $folder="../images/articole/";

        $new_file_name = strtolower($file);

        $final_file=str_replace(' ','-',$new_file_name);

        //collect form data
        extract($_POST);
        extract($_FILES);

        //very basic validation
        if($postTitle ==''){
            $error[] = 'Please enter the title.';
        }

        if($postDesc ==''){
            $error[] = 'Please enter the description.';
        }

        if($postCont ==''){
            $error[] = 'Please enter the content.';
        }
        if(move_uploaded_file($file_loc,$folder.$final_file)) {
        if(!isset($error)){
            try {

                //insert into database
                $stmt = $db->prepare('INSERT INTO blog_posts (postTitle,postDesc,postCont,postImage,postDate) VALUES (:postTitle, :postDesc, :postCont, :final_file, :postDate)') ;
                $stmt->execute(array(
                    ':postTitle' => $postTitle,
                    ':postDesc' => $postDesc,
                    ':postCont' => $postCont,
                    ':final_file' => $final_file,
                    ':postDate' => date('Y-m-d H:i:s')
                ));

                //redirect to index page
                header('Location: index.php?action=added');
                exit;

            } catch(PDOException $e) {
                echo $e->getMessage();
            }
        }
        }

    }

    //check for any errors
    if(isset($error)){
        foreach($error as $error){
            echo '<p class="error">'.$error.'</p>';
        }
    }
    ?>

    <form action='' method='post' enctype="multipart/form-data">

        <p><label>Title</label><br />
        <input type='text' name='postTitle' value='<?php if(isset($error)){ echo $_POST['postTitle'];}?>'></p>

        <p><label>Description</label><br />
        <textarea name='postDesc' cols='60' rows='10'><?php if(isset($error)){ echo $_POST['postDesc'];}?></textarea></p>

        <p><label>Content</label><br />
        <textarea name='postCont' cols='60' rows='10'><?php if(isset($error)){ echo $_POST['postCont'];}?></textarea></p>

        <p><label>Image</label><br />
        <input type="file" name="file" />

        <p><input type='submit' name='submit' value='Submit'></p>

    </form>

</div>

最佳答案

假设 $tmp 是你上传的文件

首先,我建议您检查上传图片的有效性。 取消注释 Exif和 php 扩展(在你的 php.ini 中,然后重新启动) 检查图像 mime 类型。

GD php extension 尝试同样的事情(不包含在 php 中) 以前检测到的 mime 类型,可以为您提供使用适当的扩展功能来调整大小。 与 GD.

最后计算调整大小的良好保留比率

if(move_uploaded_file($file_loc,$folder.$final_file))
{
    $tmp = $folder.$final_file;
    $type = exif_imagetype($tmp);
    switch($type)
    {
        case IMAGETYPE_PNG: $orig = imagecreatefrompng($tmp); break;
        case IMAGETYPE_JPEG: $orig = imagecreatefromjpeg($tmp); break;
        case IMAGETYPE_GIF: $orig = imagecreatefromgif($tmp); break;
    }

    //trying to get original size, if not, it's not valid image (cf. security)
    $size   = getimagesize($tmp);
    if(is_bool($size))
        return false;

    $w      = "800"; // this is your ratio fixer;
    $reduce = (($w * 100)/$size[0]);
    $h      = (($size[1] * $reduce)/100);

    $new    = imagecreatetruecolor($w, $h);

    imagecopyresampled($new , $orig, 0, 0, 0, 0, $w, $h, $size[0],$size[1]);

     // save resized 
    imagepng($new, $tmp);

    if(!isset($error))
    {
        try
        {

这是一个自制的脚本,但是: 也可以找ImageMagick php ext,更强大。

关于php - 使用 php 和 mysql 上传图像并调整大小而不变形图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34418848/

相关文章:

php - SQLSTATE[HY000] [1045] 用户 'root' @'114.xxx.xxx.xxx' 的访问被拒绝(使用密码 : YES)

php - 检查 url 中是否至少有 1 个大写字母的正则表达式代码是什么? (php)

html - 忽略父级 CSS 以更改子级的背景

jquery - CSS 粘性菜单高度调整不正确

php - 将 Enum '1' , '0' 转换为输出文本 PHP

javascript - 使用没有表单的Jquery ajax上传文件

php - PayPal rest api,PHP SDK,计费,我收到错误 REQUIRED_SCOPE_MISSING

html - 我在CSS中的页脚不关注我的左右内容,只关注中间内容

php - 重定向到聚焦文本区域的页面

mysql - 查找空闲房间(预订系统)