0

我的问题如下......我有一个屏幕,用户可以在其中从其计算机中选择PNG图像,使用这个:

<input id='icon' type='file' accept='image/png' style='width:400px; height:20px' onchange='llenarThumbnail(this)'>
<img id='thumb' src='#'>

当用户选择图像时,会自动显示缩略图,使用 onclick='llenar Thumbnail(this)',如下所示:

function llenarThumbnail(input){
 if (input.files && input.files[0]){
  var reader = new FileReader();
  reader.onload = function (e){
   $('#thumb').attr('src', e.target.result).width(48).height(48);
  };
  reader.readAsDataURL(input.files[0]);
 }
}

然后,当用户单击正确的按钮上传图像(不是提交按钮)时,我执行以下操作将图像编码为 Base64:

function getBase64Image(img){
 var canvas = document.createElement("canvas");
 canvas.width = img.width;
 canvas.height = img.height;
 var ctx = canvas.getContext("2d");
 ctx.drawImage(img, 0, 0);
 var dataURL = canvas.toDataURL("image/png");
 console.log(dataURL);
 return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

然后,我使用 AJAX 将此编码的图像数据发送到服务器,PHP 脚本执行以下操作:

$binary=base64_decode($imagen_data);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen($icono, 'wb');
fwrite($file, $binary);
fclose($file);

当我在这个过程中打印不同的警报时,我可以看到编码正在执行(我不太确定是否正确),并且 PHP 接收数据并创建 PNG 文件,但是当我打开图像时,图像是空的,没有数据......这就是为什么我要问这个方法是否兼容......我猜它们是因为它们都是Base64......但如果不是这个,那么我做错了什么???

拜托,我厌倦了在互联网上寻找这个!我需要一些答案!谢谢!

4

2 回答 2

1

没有看到你的 ajax POST,这里有一个Wild Guess

尝试保留前缀,直到 URL 到达 php.ini。

您使用的是哪个 php 服务器?

其他一些常见的陷阱:

  • 确保您已正确设置上传目录。
  • 确保您在上传目录上正确设置了权限。

客户端:

// create a dataUrl from the canvas
var dataURL= canvas.toDataURL();

// post the dataUrl to php
$.ajax({
  type: "POST",
  url: "upload.php",
  data: {image: dataURL}
}).done(function( respond ) {
  // you will get back the temp file name
  // or "Unable to save this image."
  console.log(respond);
});

服务器文件:upload.php

<?php

// make sure the image-data exists and is not empty
// php is particularly sensitive to empty image-data 
if ( isset($_POST["image"]) && !empty($_POST["image"]) ) {    

    // get the dataURL
    $dataURL = $_POST["image"];  

    // the dataURL has a prefix (mimetype+datatype) 
    // that we don't want, so strip that prefix off
    $parts = explode(',', $dataURL);  
    $data = $parts[1];  

    // Decode base64 data, resulting in an image
    $data = base64_decode($data);  

    // create a temporary unique file name
    $file = UPLOAD_DIR . uniqid() . '.png';

    // write the file to the upload directory
    $success = file_put_contents($file, $data);

    // return the temp file name (success)
    // or return an error message just to frustrate the user (kidding!)
    print $success ? $file : 'Unable to save this image.';

}
于 2013-07-11T20:22:36.530 回答
0

我无法让 markE 解决方案工作,不得不更改数据修改:

从 :

$parts = explode(',', $dataURL);  
$data = $parts[1];
$data=base64_decode($data)

至 :

$img = str_replace('data:image/png;base64,', '', $dataURL);
$img = str_replace(' ', '+', $img);
$data=base64_decode($img);

方法来自

于 2020-12-20T04:29:20.997 回答