0

I am from Brazil. SO, I am sorry for my bad english. I will give my best to explain what I need I am new to javascript and php...

I use a javascript where its resize the image before the upload. OK. After that, I use php to save the resized image to my server. OK.

What I need now is... how do I get this resized image and send via email using PHPMAILER ??

Here is the codes :

index.html

<!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <title>Cadastro de Foto</title>

    <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <script src="js/canvas-to-blob.min.js"></script>
    <script src="js/resize.js"></script>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

    <script type="text/javascript">

        // Iniciando biblioteca
        var resize = new window.resize();
        resize.init();

        // Declarando variáveis
        var imagens;
        var imagem_atual;

        // Quando carregado a página
        $(function ($) {

            // Quando selecionado as imagens
            $('#imagem').on('change', function () {
                enviar();
            });

        });

        /*
         Envia os arquivos selecionados
         */
        function enviar()
        {
            // Verificando se o navegador tem suporte aos recursos para redimensionamento
            if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
                alert('O navegador não suporta os recursos utilizados pelo aplicativo');
                return;
            }

            // Alocando imagens selecionadas
            imagens = $('#imagem')[0].files;

            // Se selecionado pelo menos uma imagem
            if (imagens.length > 0)
            {
                // Definindo progresso de carregamento
                $('#progresso').attr('aria-valuenow', 0).css('width', '0%');

                // Escondendo campo de imagem
                $('#imagem').hide();

                // Iniciando redimensionamento
                imagem_atual = 0;
                redimensionar();
            }
        }

        /*
         Redimensiona uma imagem e passa para a próxima recursivamente
         */
        function redimensionar()
        {
            // Se redimensionado todas as imagens
            if (imagem_atual > imagens.length)
            {
                // Definindo progresso de finalizado
                $('#progresso').html('Imagen(s) enviada(s) com sucesso');

                // Limpando imagens
                limpar();

                // Exibindo campo de imagem
                $('#imagem').show();

                // Finalizando
                return;
            }

            // Se não for um arquivo válido
            if ((typeof imagens[imagem_atual] !== 'object') || (imagens[imagem_atual] == null))
            {
                // Passa para a próxima imagem
                imagem_atual++;
                redimensionar();
                return;
            }

            // Redimensionando
            resize.photo(imagens[imagem_atual], 800, 'dataURL', function (imagem) {

                // Salvando imagem no servidor
                $.post('ajax/salvar.php', {imagem: imagem}, function() {

                    // Definindo porcentagem
                    var porcentagem = (imagem_atual + 1) / imagens.length * 100;

                    // Atualizando barra de progresso
                    $('#progresso').text(Math.round(porcentagem) + '%').attr('aria-valuenow', porcentagem).css('width', porcentagem + '%');

                    // Aplica delay de 1 segundo
                    // Apenas para evitar sobrecarga de requisições
                    // e ficar visualmente melhor o progresso
                    setTimeout(function () {
                        // Passa para a próxima imagem
                        imagem_atual++;
                        redimensionar();
                    }, 1000);

                });

            });
        }

        /*
         Limpa os arquivos selecionados
         */
        function limpar()
        {
            var input = $("#imagem");
            input.replaceWith(input.val('').clone(true));
        }
    </script>
</head>

<body>

<div class="container">

    <h1>Cadastro de Foto</h1>

    <form method="post" action="#" role="form">

        <div class="progress">
            <div id="progresso" class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="0"
                 aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>
        </div>

        <div class="form-group row">

            <div class="col-xs-12">
                <input id="imagem" type="file" accept="image/*" multiple/>
            </div>

        </div>

    </form>

</div>

</body>
</html>

Below is the php where save the resized file

salvar.php

<?php
   $imagem = $_POST['imagem'];
   list($tipo, $dados) = explode(';', $imagem);
   list(, $tipo) = explode(':', $tipo);
   list(, $dados) = explode(',', $dados);
   $dados = base64_decode($dados);
   $nome = md5(uniqid(time()));
   file_put_contents("../img/{$nome}.jpg", $dados);
 ?> 

Ok.. After saved the resized file, I need to send this file via email using phpmailer.. to my own email address.. Once I am collecting data.

How do I do that ?? please, help me

mageDev0688
  • 566
  • 4
  • 27
ALessandro
  • 25
  • 7

2 Answers2

0

here is the resize.js

window.resize = (function () {

'use strict';

function Resize() {
    //
}

Resize.prototype = {

    init: function(outputQuality) {
        this.outputQuality = (outputQuality === 'undefined' ? 0.8 : outputQuality);
    },

    photo: function(file, maxSize, outputType, callback) {

        var _this = this;

        var reader = new FileReader();
        reader.onload = function (readerEvent) {
            _this.resize(readerEvent.target.result, maxSize, outputType, callback);
        }
        reader.readAsDataURL(file);

    },

    resize: function(dataURL, maxSize, outputType, callback) {

        var _this = this;

        var image = new Image();
        image.onload = function (imageEvent) {

            // Resize image
            var canvas = document.createElement('canvas'),
                width = image.width,
                height = image.height;
            if (width > height) {
                if (width > maxSize) {
                    height *= maxSize / width;
                    width = maxSize;
                }
            } else {
                if (height > maxSize) {
                    width *= maxSize / height;
                    height = maxSize;
                }
            }
            canvas.width = width;
            canvas.height = height;
            canvas.getContext('2d').drawImage(image, 0, 0, width, height);

            _this.output(canvas, outputType, callback);

        }
        image.src = dataURL;

    },

    output: function(canvas, outputType, callback) {

        switch (outputType) {

            case 'file':
                canvas.toBlob(function (blob) {
                    callback(blob);
                }, 'image/jpeg', 0.8);
                break;

            case 'dataURL':
                callback(canvas.toDataURL('image/jpeg', 0.8));
                break;

        }

    }

};

return Resize;}());
ALessandro
  • 25
  • 7
0

Please try the below Code to send email using PHPMAILER:

<?php 
require_once 'class.phpmailer.php';
$mail = new PHPMailer();
// Now you only need to add the necessary stuff

// HTML body

$body = "</pre>
<div>";
$body .= " Hello Dimitrios
";
$body .= "<i>Your</i> personal photograph to this message.
";
$body .= "Sincerely,
";
$body .= "phpmailer test message ";
$body .= "</div>" ;

// And the absolute required configurations for sending HTML with attachement
$fileName = 'path_of_image/image.jpg'; 
$mail->AddAddress("sendemailto@mail.zz", "My-webpage Website");
$mail->Subject = "test for phpmailer-3";
$mail->MsgHTML($body);
$mail->AddAttachment($fileName);
if(!$mail->Send()) {
echo "There was an error sending the message";
exit;
}
echo "Message was sent successfully";

?>

Updated Code

<?php 
    require_once 'class.phpmailer.php';
    $mail = new PHPMailer();
    // Now you only need to add the necessary stuff

    // HTML body

    $imagem = $_POST['imagem'];
    list($tipo, $dados) = explode(';', $imagem);
    list(, $tipo) = explode(':', $tipo);
    list(, $dados) = explode(',', $dados);
    $dados = base64_decode($dados);
    $nome = md5(uniqid(time()));
    file_put_contents("img/{$nome}.jpg", $dados);

    $body = "</pre>
    <div>";
    $body .= " Hello Dimitrios
    ";
    $body .= "<i>Your</i> personal photograph to this message.
    ";
    $body .= "Sincerely,
    ";
    $body .= "phpmailer test message ";
    $body .= "</div>" ;

    // And the absolute required configurations for sending HTML with attachement
    $fileName = 'img/'.$nome.'.jpg'; 
    $mail->AddAddress("sendemailto@mail.zz", "My-webpage Website");
    $mail->Subject = "test for phpmailer-3";
    $mail->MsgHTML($body);
    $mail->AddAttachment($fileName);
    if(!$mail->Send()) {
    echo "There was an error sending the message";
    exit;
    }
    echo "Message was sent successfully";

    ?>
mageDev0688
  • 566
  • 4
  • 27
  • I am confuse. I will try explain better. Everytime a new client fill a form and attach a image, it get resized with javascript and saved to a folder. I need a script where to each new image saved, the script load this new image and send to my email account ?? got it ??Load the resized image and send to me.... each new image uploaed... send to me after resized save in the folder. – ALessandro Jul 07 '17 at 07:10
  • What is your confusion, you have to pass only `$filename` in `$mail->AddAttachment()` method. – mageDev0688 Jul 07 '17 at 07:14
  • you can add above code in the `ajax/salvar.php` after your image upload code. – mageDev0688 Jul 07 '17 at 07:17
  • can you please show me that inside the ajax/salver.php ?? – ALessandro Jul 07 '17 at 07:27
  • show me how stay the entire code of the salvar.php, please ? – ALessandro Jul 07 '17 at 07:28
  • can you please show me exactly how would stay the file salvar;php with the code that you showed me ?? I am confuse once the salvar.php save the .jpg file random names.. – ALessandro Jul 07 '17 at 07:51
  • Sure, I am updating my answer within 5 minutes. – mageDev0688 Jul 07 '17 at 09:05
  • friend. Sorry for not answering before. I was traveling and arrived right now. I am going to try your updated script and will let you know tomorrow, ok ? I arrived very tired after 12 hours car driving.. but I would like to thank you in advance. I will let you know the result tomorrow. – ALessandro Jul 10 '17 at 05:16
  • ok no issue you will try and let me know if you face any issue. – mageDev0688 Jul 10 '17 at 07:18
  • HI magedev !! Worked great !! I awesome !! thank you very much for your help !! very appreciated !! – ALessandro Jul 10 '17 at 18:19
  • Your most welcome!! So happy to know that it solved your problem :) Please accept my answer. – mageDev0688 Jul 10 '17 at 23:28
  • DOne !!. Hey @magedev0688. I have another doubt... How do I get the results from POST using ob_start twice in two differents pages ?? ?? – ALessandro Jul 11 '17 at 14:38
  • I can't understand your question. Could you please share the code and let me know what you want to exactly? – mageDev0688 Jul 12 '17 at 04:29
  • How can I post a entire code here ??better yet... can you please share you skype with me ?? – ALessandro Jul 12 '17 at 15:02