问题描述:

I have the following table in db:

IMAGES

  • image_id (1)
  • image_name (imagename.jpg)

But on the server I have 5 versions of same image.

imagename_500.jpg

imagename_200.jpg

imagename_100.jpg

and so .... where imagename is a uniqid().

So in this moment I get the imagename, explode the . append suffix and extension in controller and display on view.

Is this the best practice or should I add another column for extension?Or should I save all 5 names in 5 columns?

Then the next problem is how do I get the imagename with suffix from model?

This is my method from model:

 function entries_by_limit($start, $limit) {

$this->db->select('a.*');

$this->db->select('b.nume_imagine', false);

$this->db->from("$this->_table a");

$this->db->join('imagini_produse b', "b.$this->_primary_key = a.id_produs", "left");

$this->db->limit($limit, $start);

$result = $this->db->get();

//print_r($this->db->last_query());

return $result->result();

}

But i wanna keep my controller clean and don't wanna make some explode there.

So the second question is how can I get my image by passing the resolution as 3rd param and process the image name in model?

$data['products'] = $this->products->entries_by_limit($start, $limit, 500);

and return the image as imagename_500.jpg

网友答案:

i think it's better idea to keep you database as it is
store just the file name and then pass the file name to a function with 2 parameters as shown below

function  img_size ($img, $size) {
    $info = pathinfo($img);
$img_name = $info['filename'];
$img_ext = $info['extension'];
$img_size = $img_name . '_' . $size .'.'. $img_ext ;
 return $img_size ;
}


$img = 'imagename.jpg';
$img_200 = img_size($img, 300);
echo $img_200 ;

you will get this as a result
imagename_300.jpg
you pass the image name and the size you want so in the future if you add more sizes or remove a size that will be away from database

网友答案:

This solved my problem:

    function entries_by_limit($start, $limit, $rez) {
    $this->db->select('a.*');
    $this->db->select('b.nume_imagine', false);
    $this->db->from("$this->_table a");
    $this->db->join('imagini_produse b', "b.$this->_primary_key = a.id_produs", "left");
    $this->db->limit($limit, $start);
    $result = $this->db->get();
    foreach($result->result() as $single) {

        if($single->nume_imagine)
            $single->nume_imagine = $this->parse_image($single->nume_imagine, $rez);
    }

    return $result->result();
}

function parse_image($image_name, $rez){

        $image = explode('.', $image_name);
        return $image[0].'_'.$rez.'.'.$image[1];
}

and call from controller:

$data['produse']        = $this->produse->entries_by_limit($start, $limit, '270');

Don't know if is a good practice.

相关阅读:
Top