我现在在Codeigniter工作,在上传时调整图片大小有一些问题。我尝试了一些代码,但工作不正常。下面我添加了文件上传功能:
public function add_to_event()
{
if (!empty($_FILES['event_image']['name'])) {
$config['upload_path'] = './images/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['image']['name']; //image upload-url to db and image to system directory
//Load upload library and initialize configuration
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('event_image')) {
$uploadData = $this->upload->data();
$image = $uploadData['file_name'];
} else {
$image = '';
}
}
else {
$image = '';
}
$image ="http://localhost/infi-admin/images/$image";
$event_title=$this->input->post('event_title');
$event_description=$this->input->post('event_description');
$this->load->model('User_model');
$data= array('event_title' =>$event_title ,
'event_description' =>$event_description,
'event_image'=>$image
);
$this->User_model->add_to_event_model($data);
redirect('Site/event_view');
}
这是我的控制器功能,可以将图像与其他字段一起上传
答案 0 :(得分:0)
这可能有助于您入门:
$config['image_library'] = 'gd2';
$config['source_image'] = '/path/to/image/mypic.jpg';
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 75;
$config['height'] = 50;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
if (!empty($_FILES['event_image']['name'])) {
$config['upload_path'] = './images/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['image']['name'];//image upload-url to db and image to system directory
//Load upload library and initialize configuration
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('event_image')) //name in db
{
$uploadData = $this->upload->data();
$image = $uploadData['file_name'];
$config['image_library'] = 'gd2';
$config['source_image'] = $config['upload_path'].$config['file_name']
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 75;
$config['height'] = 50;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
// image name will be $config['upload_path'].$config['file_name'].'_thumb.jpg'
}
else {
$image = '';
}
}
else {
$image = '';
}
$image ="http://localhost/infi-admin/images/$image";
$event_title=$this->input->post('event_title');
$event_description=$this->input->post('event_description');
$this->load->model('User_model');
$data= array('event_title' =>$event_title ,
'event_description' =>$event_description,
'event_image'=>$image);
$this->User_model->add_to_event_model($data);
redirect('Site/event_view');
}
这绝对应该被抽象为模型或服务。控制器不需要知道如何完成图像上传和调整大小。在保存之前,还要考虑重命名图像文件并在名称中添加一些随机性。