首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用CodeIgniter Imagick将图像从控制器传递到视图

如何使用CodeIgniter Imagick将图像从控制器传递到视图
EN

Stack Overflow用户
提问于 2018-07-25 05:37:49
回答 1查看 1.2K关注 0票数 0

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

控制器代码:

代码语言:javascript
复制
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;    
    }

  }
}  

查看代码:

代码语言:javascript
复制
<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。如何在视图中加载图像?

EN

回答 1

Stack Overflow用户

发布于 2018-07-25 09:24:35

第1张

只需通过json将新创建的图像url传递给ajax成功函数,并将img src修改为该url。

HTML:

代码语言:javascript
复制
<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:

代码语言:javascript
复制
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

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

代码语言:javascript
复制
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:

代码语言:javascript
复制
<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>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51507898

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档