почему redirect () не позволяет мне завершить вызов функции? - PullRequest
1 голос
/ 12 сентября 2011

Итак, я пишу функцию, которая позволит мне добавить идентификатор из одной таблицы базы данных в другую, чтобы связать их, но я натолкнулся на некоторое недоразумение и, похоже, не могу понять, что делать.любая помощь будет сильно оценена.

прошу прощения за то, что я немного грязный код, я пробовал много разных решений, которые, кажется, не работают.

class photo_modle extends CI_Model {

var $gallery_path;
var $image_name;
var $row;
var $gid; // gallary ID
var $iid; // image ID
function photo_modle() {
ob_start();
    $this->gallery_path = realpath(APPPATH . '../images');
}

function uploadPhoto() {


    $config = array(
        'allowed_types' => 'jpg|jpeg',
        'upload_path' => $this->gallery_path,
    );

    $this->load->library('upload', $config);
    $this->upload->do_upload();
    $image_data = $this->upload->data();

    $this->image_name = $image_data['file_name'];
    $config = array(
        'source_image' => $image_data['full_path'],
        'new_image' => realpath($this->gallery_path . '/thumb/normal/'),
        'width' => 248,
        'height' => 198,
        'maintain_ratio' => false
    );

    $this->load->library('image_lib', $config);
    $this->image_lib->resize();

    $data = array(
        'image_name' => $this->image_name,
        'description' => $this->input->post('description'),
        'name' => $this->input->post('name')

    );



    $str = $this->db->insert_string('images', $data);

    $this->db->query($str);
    $this->iid = $this->db->insert_id();


    $grayscale_path = '/Applications/XAMPP/xamppfiles/htdocs/images/thumb/normal/' . $this->image_name;
    header('Content-type: image/jpeg');
    $img = imagecreatefromjpeg($grayscale_path);
    imagefilter($img, IMG_FILTER_GRAYSCALE);
    imagejpeg($img, '/Applications/XAMPP/xamppfiles/htdocs/images/thumb/rollover/' . $this->image_name, 100);
    imagedestroy($img);
    $ndata = array (
        'image_name' => $this->image_name,
        'description' => $this->input->post('description'),
        'name' => $this->input->post('name'),
        'id' => $this->iid
         );

    $this->session->set_userdata($ndata);


}




function add_new_gallery() {


    $ndata = array(
        'gallery_name' => $this->input->post('gallery_name'),
        'description' => $this->input->post('gallery_description'),
     ); 

     $n_str = $this->db->insert('gallery', $ndata);
    // this is the only place where i can put the redirect without it returning errors
    // but if i do it here it does not pass back the gid variable which i need. 
    // I also should mention that I have a  header('Content-type: image/jpeg'); above all of
    // this, and that is why I have to do a redirect, so that I don't get an error. and that 
    // header code is nessasary, for I am doing some photo manipulation that requires it. 
     redirect('site/uploaded'); 
     $this->db->query($n_str);
     $this->gid = $this->db->insert_id();

     // I was trying to send that info in the session, but even that did not work because of the 
     // redirect
     $sdata = array(
         'gallery_id' => $this->gid
     );

     $this->session->set_userdata($sdata);


}
// this function needs the info that is not getting passed. 
function addId() {
      $sdata = array('gallery_id' => $this->session->userdata('gallery_id'));
     $where = "id = ".$this->session->userdata('image_id'); 
     $str = $this->db->update_string('images', $sdata, $where);

     $this->db->query($str);
}

любому, кто может помочь, спасибо, оооочень много за ваше время.любые предложения будут великолепны!

1 Ответ

2 голосов
/ 14 сентября 2011

Вам не нужно отправлять заголовок Content-type: image/jpeg, если вы просто манипулируете изображением и сохраняете результаты в файл.

Это только необходимо при отправке изображения в браузер.

Вы можете запутаться в том, как работает imagejpeg , поскольку он имеет двойственное поведение.imagejpg может:

  • Вывести изображение прямо в браузер, если вы не передаете его $filename.Конечно, вы должны предупредить браузер, что он ожидает данные изображения, именно тогда вы отправляете ему заголовок типа контента.

  • Сохраните изображение в файл, если вы дадите ему $filename.

В вашем случае вы передаете ему $filename, чтобы изображение было сохранено на диск.Но вы также отправляете Content-type: image/jpeg, так что ваш браузер ожидает получения данных изображения, что никогда не происходит, тогда оно «не может быть отображено, поскольку содержит ошибки».

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...