how to pass image from controller to view with CodeIgniter Imagick

萝らか妹 提交于 2019-12-13 20:47:07

问题


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?


回答1:


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:

<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">
        <img src="http://via.placeholder.com/300x400">
    </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",
                    method: "POST",
                    data: new FormData(this),
                    contentType: false,
                    cache: false,
                    processData: false,
                    dataType: 'json',
                    success: function (data)
                    {
                        if (data.success == true) {
                            $('#result').find('img').attr('src', data.file);
                        } else {
                            alert(data.msg);
                        }
                    }
                });
            }
        });
    });
</script>
</body>

PHP:

try {
    if (!isset($_FILES["userfile"])) {
        throw new Exception('No file uploaded.');
    }
    $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) {
        throw new Exception('An error occured.');
    }
    $image = new Imagick($tmpFile);
    $new_file = "assets/images/{$fileName}";
    $image->equalizeImage();
    $image->writeImage(FCPATH . '/' . $new_file);
    echo json_encode(array('success' => true, 'file' => base_url($new_file)));
} catch (Exception $e) {
    echo json_encode(array('success' => false, 'msg' => $e->getMessage()));
}

Take 2

This is the only way you can download the file without having it saved on the server.

class Test extends CI_Controller {

    public function index() {
        $this->load->view('test');
    }

    public function eq() {
        try {
            if (!isset($_FILES['userfile'])) {
                throw new Exception('No file uploaded.');
            }
            $file_error = $_FILES['userfile']['error'];
            if ($file_error !== 0) {
                throw new Exception('Error uploading: Code ' . $file_error);
            }
            $tmp_file = $_FILES['userfile']['tmp_name'];
            list($width, $height) = getimagesize($tmp_file);
            if ($width == null && $height == null) {
                throw new Exception('An error occured.');
            }
            $image = new Imagick($tmp_file);
            $image->equalizeImage();
            $encoded_file = base64_encode($image->getimageblob());
            echo json_encode(array('success' => true, 'type' => $image->getimageformat(), 'file' => $encoded_file));
        } catch (Exception $e) {
            echo json_encode(array('success' => false, 'msg' => $e->getMessage()));
        }
    }

    public function download() {
        $contents = $this->input->post('image_contents');
        $extension = $this->input->post('extension');
        if (is_null($contents) || is_null($extension)) {
            show_error('Image contents empty');
        }
        $name = 'equalized_image.' . strtolower($extension);
        $contents = base64_decode($contents);
        $this->load->helper('download');
        force_download($name, $contents);
    }

}

HTML:

<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
        <script>
            function readURL(input) {
                if (input.files && input.files[0]) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        $('#original-image')
                                .attr('src', e.target.result);
                    };
                    reader.readAsDataURL(input.files[0]);
                }
            }
            $(document).ready(function () {
                $('#download').hide();
                $('#upload_form').on('submit', function (e) {
                    e.preventDefault();
                    if ($('#userfile').val() == '')
                    {
                        alert("Please Select the File");
                    } else
                    {
                        $.ajax({
                            url: "/neou_cms/test/eq",
                            method: "POST",
                            data: new FormData(this),
                            contentType: false,
                            cache: false,
                            processData: false,
                            dataType: 'json',
                            success: function (data)
                            {
                                console.log(data);
                                if (data.success == true) {
                                    var image_content = 'data:image/' + data.type + ';base64,' + data.file;
                                    $('#eq-image').attr('src', image_content);
                                    $('#image_contents').attr('value', data.file);
                                    $('#extension').attr('value', data.type);
                                    $('#download').show();
                                } else {
                                    alert(data.msg);
                                }
                            }
                        });
                    }
                });

            });
        </script> 
    </head>
    <body>
        <form method="post" id="upload_form" enctype="multipart/form-data">
            <table border="1">
                <tr>
                    <td colspan="2"><input type="file" name="userfile" size="20" onchange="readURL(this);"></td>
                </tr>
                <tr>
                    <td>Original Image</td>
                    <td>Equalized Image</td>
                </tr>
                <tr>
                    <td>
                        <img id="original-image" src="http://via.placeholder.com/300x400" width="300" height="auto">
                    </td>
                    <td>
                        <img id="eq-image" src="http://via.placeholder.com/300x400" width="300" height="auto">
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="submit" name="upload" id="upload" value="Apply" class="btn btn-info">
                    </td>
                </tr>
            </table>  
        </form>
        <form method="post" action="/neou_cms/test/download">
            <input type="hidden" value="" name="image_contents" id="image_contents">
            <input type="hidden" value="" name="extension" id="extension">
            <input type="submit" name="download" id="download" value="Download Image">
        </form>
    </body>
</html>


来源:https://stackoverflow.com/questions/51507898/how-to-pass-image-from-controller-to-view-with-codeigniter-imagick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!