显示上传的图像

时间:2012-12-25 15:16:32

标签: php javascript

我正在尝试使用Ajax上传/调整图像大小,然后将其显示在浏览器中,而不是将其保存到文件中。我期待有一个形象,而不是我有一堆胡言乱语。

可行吗?或者我不能并且需要采取其他措施,例如保存到文件然后采取其路径?或者也许使用画布?

感谢您的时间。

HTML

<form enctype="multipart/form-data" action="file.php" method="Post" id="form">
  <input type="file" name="user_image">
  <input type="submit" value="Submit" name="submit">
</form>
<div id="blah"></div>

的Javascript

//using jquery-form.js
$('#form').on('submit', function(e) {
  e.preventDefault();
  $(this).ajaxSubmit({
    target: '#blah',
    success:  function(){}
  });
});

PHP

$img_width = imagesx($this->image);
$img_height = imagesy($this->image);
$image = imagecreatefromjpeg($_FILE['user_image']['tmp_name']);
$resized_image = imagecreatetruecolor(300, 300);
imagecopyresampled($resized_image, $image, 0, 0, 0, 0, 300, 300, $img_width, $img_height);
header('Content-Type:image/jpeg');
imagejpeg($resized_image);

2 个答案:

答案 0 :(得分:4)

在PHP中执行此操作

ob_start();
// header("Content-type: image/jpeg"); // fairly sure you won't need this
imagejpeg($resized_image);
echo base64_encode(ob_get_clean());
die;

假设你有HTML格式

<img id="theimage" />

然后在JS

success:  function(data){
    $('#theimage').attr('src', 'data:image/jpeg;base64,' + data);
}

答案 1 :(得分:0)

您正在尝试使用ajax获取原始jpeg数据。您不应该执行ajax上传,而是直接发送表单以查看已调整大小的图像。如果这不是您想要的,那么您需要将原始jpeg数据编码为base64编码的数据URL并将其作为src元素的<img>属性插入。

相关问题