簡體   English   中英

上傳前縮小圖片尺寸

[英]Reduce image size before upload

我有一個包含一些數據和 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('dm-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 函數會在上傳后減小圖片大小

<?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 或更大的圖像

PHP 在服務器上運行,除非圖像上傳到服務器,否則您無法壓縮圖像。 但是您可以在上傳之前使用 Javascrypt 壓縮圖像。 根據您使用的框架,有很多解決方案可以解決這個問題。 現代網站通常會在媒體上傳之前對其進行壓縮以減少帶寬,這與您提到的原因相同。

如果你使用React, AngularJS or VueJS你可以使用browser-image-compression npm 包。 這個庫有很多功能。 您可以通過降低圖像 JPEG 質量或僅更改尺寸來壓縮。

如果您所關心的只是縮小尺寸(寬度和高度),並沒有與質量你可以只使用一個簡單Javascrypt功能顯示在這里 為方便起見,我復制了其中的一部分。

// 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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM