dongling4383 2015-12-22 15:11 采纳率: 100%
浏览 68

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

I have the code that uploads the image and store it in database, but I need to resize that image on uploading without deforming it. I'm trying not to use js, but if its needed please use, and help me.

Here is my file 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>

</div>
  • 写回答

1条回答 默认 最新

  • doujianjian2060 2015-12-22 15:18
    关注

    Assuming $tmp is your uploaded file

    First, i recommand you to check the validity of uploaded image. uncomment Exif and php extension (in you php.ini, and restart) To check the image mime type.

    Try the same thing with GD php extension (not included with php) Previous detected mime type, can provide you to use the proper extension functions to use for resizing. with GD.

    And finally calculating the good preserved ratio to your resize.

    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
            {
    

    This is a self made script, but: You can also looking for ImageMagick php ext, more stronger.

    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值