slier
slier

Reputation: 6740

Displaying uploaded image

I'm trying to upload/resize an image using Ajax and then display it in the browser instead of saving it to a file. I'm expecting to have an image, instead I got a bunch of gibberish.

Is it doable? Or I can't and need to resort to something else like saving to a file and then take its path? Or perhaps using canvas?

Thanks for your time.

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);

Upvotes: 0

Views: 161

Answers (2)

Popnoodles
Popnoodles

Reputation: 28409

In your PHP do this

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

assuming you have in HTML

<img id="theimage" />

then in JS

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

Upvotes: 4

Licson
Licson

Reputation: 2271

You're trying to get the raw jpeg data using ajax.You should not perform an ajax upload but instead send the form directly to see the resized image. If this is not what you want, then you'll need to encode the raw jpeg data to a base64-encoded data url and insert that as the src property of an <img> element.

Upvotes: 0

Related Questions