php - 附加base64 img时获取黑色图片

标签 php base64

我正在尝试发送一封带有图像附件的电子邮件。我可以发送电子邮件,但我没有成功显示图片,它只是黑色。 php 正在接收一个 base64 字符串,它是一个图像。另外我想在不存储任何内容或在服务器上写入任何内容的情况下执行此操作。有可能的方法吗?
这就是 php 的样子。

   <?php 
    $base64 = $_POST['dataURL'];
    //define the receiver of the email 
    $to = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7f0c10121a3f121e1613511c1012" rel="noreferrer noopener nofollow">[email protected]</a>'; 
    //define the subject of the email 
    $subject = 'Test email with attachment'; 
    //create a boundary string. It must be unique 
    //so we use the MD5 algorithm to generate a random hash 
    $random_hash = md5(date('r', time())); 
    //define the headers we want passed. Note that they are separated with \r\n 
    $headers = "From:Francisco Granado\r\nReply-To: <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef988a8d828e9c9b8a9daf8a978e829f838ac18c8082" rel="noreferrer noopener nofollow">[email protected]</a>"; 
    //add boundary string and mime type specification 
    $headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\""; 
    //read the atachment file contents into a string,
    //encode it with MIME base64,
    //and split it into smaller chunks
    $attachment = base64_decode($base64); 
    //define the body of the message. 
    ob_start(); //Turn on output buffering 
    ?> 
    --PHP-mixed-<?php echo $random_hash; ?>  
    Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>" 

    --PHP-alt-<?php echo $random_hash; ?>  
    Content-Type: text/plain; charset="iso-8859-1" 
    Content-Transfer-Encoding: 7bit

    This email have attached a image file 
    For SED_WE analysis purposes. 

    --PHP-alt-<?php echo $random_hash; ?>  
    Content-Type: text/html; charset="iso-8859-1" 
    Content-Transfer-Encoding: 7bit

    <h1>SED_WE</h1>
    <p>This email have attached a image file </p> 
    <p>For SED_WE analysis purposes.</p> 

    --PHP-alt-<?php echo $random_hash; ?>-- 

    --PHP-mixed-<?php echo $random_hash; ?>  
    Content-Type: image/jpeg; name="attachment.jpeg"  
    Content-Transfer-Encoding: base64  
    Content-Disposition: attachment  

    <?php echo $attachment; ?> 
    --PHP-mixed-<?php echo $random_hash; ?>-- 

    <?php 
    //copy current buffer contents into $message variable and delete current output buffer 
    $message = ob_get_clean(); 
    //send the email 
    $mail_sent = @mail( $to, $subject, $message, $headers ); 
    //if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
    echo $mail_sent ? "Mail sent" : "Mail failed"; 
   ?>

这也是我的js:

$(document).ready(function (e) {
    var imgBase64;
    function imgToBase64(url, callback, outputFormat) {
        var canvas = document.createElement('CANVAS'); //Creates variable containing canvas in the DOM
        var canvas_context = canvas.getContext('2d'); //Creates canvas environment (context) in 2 dimensions 
        var img = new Image; // new Image instance
        img.crossOrigin = 'Anonymous'; //Cross origin textures from other URL's are permitted (see http://blog.chromium.org/2011/07/using-cross-domain-images-in-webgl-and.html) for more information
        console.log('ON LOAD IMG');
        //Image load trigger, encode image into base64
        img.onload = function () {
            //Determine canvas height and width 
            canvas.height = img.height;
            canvas.width = img.width;
            console.log('Canvas info:\n Height: ' + canvas.height + '\n Width: ' + canvas.width);
            //Draws the image raw format 
            canvas_context.drawImage(img, 0, 0);
            var dataURL = canvas.toDataURL(outputFormat || 'image/png'); //THIS IS WHERE THE MAGIC HAPPENS (img encode to base64)
            //imgBase64 = dataURL;
            $('#show-picture').attr('src', dataURL); //Change source of the #show-picture image tag to the base64 string to show preview to user 
            console.log(dataURL);
            callback.call(this, dataURL); //Callback function @param {dataURL} 
            // Clean up
            canvas = null;
        };
        img.src = url;
    }

    //Reads the path to the picture for a preview 
    function readURL(input) {
        if (input.files && input.files[0]) { //if file exist
            var reader = new FileReader(); //new instance of the file reader

            reader.onload = function (e) { //when the reader loads the chosen file...
                imgToBase64(e.target.result, function (dataURL) { //..then the is converted 
                    setDataURL(dataURL);
                });
            }
            reader.readAsDataURL(input.files[0]);
        }
    }

    function setDataURL(dataURL){
        imgBase64 = dataURL;
        console.log('setDataUrl=>'+imgBase64);
    }



    $('#take-picture').change(function () {
        readURL(this);
        console.log('ONLOAD'+imgBase64);
    });

    $('#uploadImgBtn').on('click',function(){
        var base64String= imgBase64.replace(/data:image[^;]+;base64,/,'');
        console.log('base64string'+base64String);
        $.post('php/mailer.php',base64String,function(data){alert('Success!'); console.log('response: '+data)});
    });

});

P.S:我尝试了与其他帖子不同的方法,但是没有成功或者他们在服务器上写入,这也是我第一次使用 php,所以非常欢迎任何好的建议。

最佳答案

在将数据发送到 php 的 javascript 文件中,没有 dataURL 的键名,我需要删除 data:image/* ;base64, 输出纯base64 的字符串。所以它应该是这样的:

$('#uploadImgBtn').on('click',function(){
        var base64String= imgBase64.replace(/data:image[^;]+;base64,/,'');
        console.log('base64string'+base64String);
        $.post('php/mailer.php',{dataURL:base64String},function(data){
            alert('Success!');
            console.log('response: '+data)});
    });

然后php将接收dataURL,而我所需要做的就是chunk_split该base64字符串。像这样:

  $base64 = $_POST['dataURL'];
   ...
  $attachment = chunk_split($base64);

  ...

关于php - 附加base64 img时获取黑色图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24767532/

相关文章:

ios - 在 Swift4 中获取错误的 Base64 图像

javascript - 将 base64 字符串转换为 ArrayBuffer

javascript - 如何将 "push notifications"发送到特定用户网页?

php - 使我的电子邮件表格列响应流畅的问题

php - 无法从 Google App Engine 上的 Php PDO 获取响应 header

php - 如何按顺序获取收据编号 AB0810001

image - Go - 将 base64 字符串保存到文件

php - 列出所有可能的字母组合,8 到 64 位长的字符串

curl - 如何将公钥转换为 base64 公钥?

java - JS和Java中相同图像的不同Base64字符串