I was working with CodeIgniter php, and using Imagick for some image manipulation. Now I want to upload image and after image manipulation e.g Image equalizing, I want to pass or load the equalized image from controller to view. The image is equalized and uploaded to a path, but I am unable to load the output equalized image to view page. So, kindly guide how to handle this problem?
Controller Code:
class Equalize extends CI_Controller {
public function equalize_image() {
if (isset($_FILES["userfile"])) {
$tmpFile = $_FILES["userfile"]["tmp_name"];
$ext = pathinfo($_FILES["userfile"]["name"], PATHINFO_EXTENSION);
$fileName = uniqid(rand(), true) . "." . $ext;
list($width, $height) = getimagesize($tmpFile);
if ($width == null && $height == null) {
header("Location: index.php");
return;
}
$image = new Imagick($tmpFile);
$image->equalizeImage();
$image->writeImage(FCPATH.'/assets/images' . "/" . $fileName);
header("Content-Type: image/jpeg");
echo $image;
}
}
}
View Code:
<label>Input Image</label>
<form method="post" id="upload_form" enctype="multipart/form-data">
<input type='file' name="userfile" size="20" onchange="readURL(this);"/>
<label>Orignal Image</label><br>
<img id="blah" src="#" alt="" />
<label>Equalized Image </label>
<div id="result">
</div>
<input type="submit" name="upload" id="upload" value="Apply" class="btn btn-info" />
</form>
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(200)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
$(document).ready(function(){
$('#upload_form').on('submit', function(e){
e.preventDefault();
if($('#userfile').val() == '')
{
alert("Please Select the File");
}
else
{
$.ajax({
url:"<?php echo base_url(); ?>Equalize/equalize_image",
//base_url() = http://localhost/tutorial/codeigniter
method:"POST",
data:new FormData(this),
contentType: false,
cache: false,
processData:false,
success:function(data)
{
$('#result').html(data);
}
});
}
});
});
</script>
</body>
With this code I am facing this output: https://imgur.com/85vMove. How to load the image in view?
Take 1
Just pass the newly created image url to the ajax success function via json and modify the img src to that url.
HTML:
PHP:
Take 2
This is the only way you can download the file without having it saved on the server.
HTML: