如何使用CodeIgniter Imagick从控制器传递图像以进行查看

时间:2018-07-24 21:37:49

标签: php codeigniter imagick

我正在使用CodeIgniter php,并使用Imagick进行某些图像处理。现在我想上传图像,并在图像处理(例如图像均衡)之后,我想从控制器传递或加载均衡图像以进行查看。图像被均衡并上传到路径,但是我无法将输出的均衡图像加载到查看页面。那么,请指导如何处理此问题?

控制器代码:

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

  }
}  

查看代码:

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

使用此代码,我将面对以下输出:https://imgur.com/85vMove。如何在视图中加载图像?

1 个答案:

答案 0 :(得分:1)

采取1

只需通过json将新创建的图片网址传递给ajax成功函数,然后将img src修改为该网址即可。

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

以2

这是下载文件而不将其保存在服务器上的唯一方法。

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>