【问题标题】:Reduce image size before upload上传前缩小图片大小
【发布时间】:2020-06-08 03:33:15
【问题描述】:

我有一个表格,其中包含一些数据和 2 个用于上传图片的输入,我已经阅读了网站上的其他问题,但答案确实很多。我只需要在上传之前减小图像的大小,以便用户更快。我无法理解的是如何缩小图像并从mailer.php 中检索它。

<?php

    $nome        = $_POST["nome-locale"];
    $email       = $_POST["email"];
    $telefono    = $_POST["telefono"];
    $indirizzo   = $_POST["indirizzo"];
    $civico      = $_POST["civico"];
    $citta       = $_POST["citta"];
    $provincia   = $_POST["provincia"];
    $cap         = $_POST["cap"];
    $titolare    = $_POST["titolare"];
	$cf          = $_POST["codice_fiscale"]; 
    $declaration = isset($_POST["declaration"]) ? $_POST['declaration'] : 'No';
    $newsletter  = isset($_POST["newsletter"]) ? $_POST['newsletter'] : 'No';
    $data        = date('d-m-Y'); 


    $body = "<br>nome-locale:" . $nome . "<br>Email:" . $email . "<br>TelefonoLocale:" . $telefono . "<br>Indirizzo:" . $indirizzo . "<br>Civico:" . $civico . "<br>Città:" . $citta . "<br>Provincia:" . $provincia . "<br>Cap:" . $cap . "<br>Nome titolare:" . $titolare . "<br>CF:" . $cf . "<br>Declaration:" . $declaration . "<br>newsletter:" . $newsletter;


    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;

    require 'PHPMailer/src/Exception.php';
    require 'PHPMailer/src/PHPMailer.php';
    require 'PHPMailer/src/SMTP.php';
    // Instantiation and passing `true` enables exceptions
    $mail = new PHPMailer(true);

    $mail->isSMTP(); // Send using SMTP
    $mail->Host       = x // Set the SMTP server to send through
    $mail->SMTPAuth   = true; // Enable SMTP authentication
    $mail->Username   = 'x // SMTP username
    $mail->Password   = 'x; // SMTP password
    $mail->SMTPSecure = 'ssl'; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
    $mail->Port       = 465; // TCP port to connect to

    if (array_key_exists('menu1', $_FILES) && array_key_exists('menu2', $_FILES)) {
        try {
            //Server settings
            // First handle the upload
            // Don't trust provided filename - same goes for MIME types
            // See http://php.net/manual/en/features.file-upload.php#114004 for more thorough upload validation
            $menu1_filename = $_FILES['menu1']['name'];
            $menu2_filename = $_FILES['menu1']['name'];

            $menu1 = tempnam(sys_get_temp_dir(), hash('sha256', $menu1_filename));
            $menu2 = tempnam(sys_get_temp_dir(), hash('sha256', $menu2_filename));

            if (move_uploaded_file($_FILES['menu1']['tmp_name'], $menu1) &&
                move_uploaded_file($_FILES['menu2']['tmp_name'], $menu2)) {
                // Upload handled successfully
                // Now create a message
                //Recipients
                $mail->setFrom('feed@vaimenu.it', $data);
                $mail->addAddress('feed@vaimenu.it'); // Add a recipient
                $mail->isHTML(true); // Set email format to HTML
                $mail->Subject = ('Iscrizione: ' . $nome);
                $mail->Body = $body;
                $mail->AltBody = 'Iscrizione ricevuta da landing page';

                // Attach the uploaded file
                $mail->AddAttachment($menu1, $menu1_filename);
                $mail->AddAttachment($menu2, $menu2_filename);
                $mail->send();

                $mail->ClearAllRecipients();
                $mail->clearAddresses();
                $mail->ClearAttachments();

                $mail->isHTML(true);
                $mail->Subject = ('Benvenuto, ' . $nome);
                $mail->setFrom('feed@vaimenu.it', 'Vaimenu.it');
                $mail->addAddress($email);

                $message = file_get_contents('Benvenuto.html');
                $message = str_replace('%Nome%', $nome, $message);

                $mail->MsgHtml($message);

                if (!$mail->send()) {
                    $response['error']   = true;
                    $response['message'] = "Message could not be sent. Some thing went wrong Mailer Error: " . $mail->ErrorInfo;
                } else {
                    $response['success'] = true;
                }
            } else {
                $response['error']   = true;
                $response['message'] = 'Failed to move file to ' . $menu1;
            }

            echo json_encode($response);
        } catch (Exception $e) {
            $response['error']   = true;
            $response['message'] = "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";

            echo json_encode($response);
        }
    }
?>
<form role="form" method="post" id="myform" action="mailer.php" enctype="multipart/form-data" >
.......
.......
<div class="form-group was-validated">
								<label class="control-label">Menu1</label>
								<input type="file" name="menu1" accept=".jpg,.jpeg,.pdf,.png" required>
							</div>
							<div class="progress">
								<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
							</div>
							<br>
                          <div class="form-group was-validated ">
			    <label class="control-label">Menu2</label>
								<input type="file" name="menu2"  accept=".jpg,.jpeg,.pdf,.png" required>
							</div>
							<div class="progress">
								<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
							</div>
              
              
              ....
              <button class="btn btn-success btn-lg fa-pull-right" type="submit">Finito!</button>
              </form>

【问题讨论】:

  • “我只需要在上传之前减小图片的大小” ... PHP 在服务器上运行,所以它不能对图片做任何事情 直到它被上传。
  • @Fabio “上传前”是什么意思?你的意思是你想在上传到服务器之前用 JavaScript 缩小图像吗?还是您的意思是在通过电子邮件发送之前,您需要在服务器上通过 PHP 缩小图像?
  • 使用php上传后可以调整图片大小
  • 是的,不是用 PHP 调整大小,我的意思是图像必须在用户按下提交按钮之前调整大小,以便在发送表单时更快。

标签: javascript php html image image-compression


【解决方案1】:

PHP 在服务器上运行,除非将图像上传到服务器,否则您无法压缩图像。但是您可以在上传之前使用 Javascrypt 压缩图像。根据您使用的框架,有很多解决方案可以解决这个问题。现代网站通常会在上传媒体之前对其进行压缩以减少带宽,这与您提到的原因相同。

如果你使用React, AngularJS or VueJS,你可以使用browser-image-compression npm 包。这个库有很多功能。您既可以通过降低图像 JPEG 质量来进行压缩,也可以只更改尺寸。

如果您只关心减小尺寸(宽度和高度)而与质量无关,您可以使用简单的 Javascrypt 函数,如 here 所示。为了方便起见,我复制了其中的一部分。

// from an input element
var filesToUpload = input.files;
var file = filesToUpload[0];

var img = document.createElement("img");
var reader = new FileReader();  
reader.onload = function(e) {img.src = e.target.result}
reader.readAsDataURL(file);

var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);

var MAX_WIDTH = 800;
var MAX_HEIGHT = 600;
var width = img.width;
var height = img.height;

if (width > height) {
  if (width > MAX_WIDTH) {
    height *= MAX_WIDTH / width;
    width = MAX_WIDTH;
  }
} else {
  if (height > MAX_HEIGHT) {
    width *= MAX_HEIGHT / height;
    height = MAX_HEIGHT;
  }
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);

var dataurl = canvas.toDataURL("image/png")

【讨论】:

    【解决方案2】:

    这个PHP函数会在上传后缩小图片大小

    <?php  
        // Compress image
        function compressImage($source, $destination, $quality) {
    
            $info = getimagesize($source);
    
            if ($info['mime'] == 'image/jpeg') {
                $image = imagecreatefromjpeg($source);
            } elseif ($info['mime'] == 'image/gif') {
                $image = imagecreatefromgif($source);
            } elseif ($info['mime'] == 'image/png') {
                $image = imagecreatefrompng($source);
            }
    
            imagejpeg($image, $destination, $quality);
    
        }
    ?>
    

    保存到目录

    $img_dir = "img/";
    // $img = ""; your image
    
    compressImage($_FILES["img"]["tmp_name"], $img_dir.$img, 60);
    

    最适合小于 10MB 或更大的图片

    【讨论】:

    • 但是使用此代码,用户必须上传文件,并且在调整大小后,发送表单并不快
    • 先验证图片大小,可以设置最大。大小为 5mb 以加快压缩速度。
    • 为什么允许用户上传更大的 MB 大小的图片到邮件/通过邮件
    猜你喜欢
    • 1970-01-01
    • 2014-06-22
    • 2011-08-06
    • 2017-09-06
    • 2014-08-26
    • 2021-09-13
    • 2012-05-07
    相关资源
    最近更新 更多