Yii 1.0 Display Image Form Database

Before save the image into database, i created one 'text' field in mysql table to save the image code.

We can show the image in CDetailview from database table of yii framework. Here i used showphoto_from_database() function to display the image from database. showproof_from_image_folder() is used to fetch uploaded image url from database and display.

view.php


<?php $this->widget('zii.widgets.CDetailView', array(
        'data'=>$model,
        'attributes'=>array(	
        array(
            'name'=>'photo_id',
            'type'=>'raw',
            'value'=>$model->showphoto_from_database(),            
        ),
        array(
            'name'=>'vproof_id',
            'type'=>'raw',
            'value'=>$model->showproof_from_image_folder(),
        )
    ),
)); 
?>

model.php

Image From Database

public function showphoto_from_database(){
    if($this->bitmap!=''){
        //return "data:image/png;base64,".$photomodel->bitmap;
        return CHtml::image("data:image/png;base64,".$photomodel->bitmap,
            'No Image',
            array('width'=>150,'height'=>100)
        );
    }else{
        $url=Yii::app()->baseUrl."/img/noimage.jpg";                
        return CHtml::image($url,'No Image');
    }
}
Image From Database With Link

<?php
// From Database 
public function showphoto_from_database(){
    if($this->photo_id!=''){
        $photomodel=Photos::model()->findByPk($this->photo_id);
        if($photomodel && $photomodel->bitmap!=''){
            //return "data:image/png;base64,".$photomodel->bitmap;
            $img="data:image/png;base64,".$photomodel->bitmap;
            //return image with link
            return "<a href='".$img."' target='_blank'>". 
            CHtml::image($img,'No Image',array('width'=>100,'height'=>100))."</a>";
        }else{
            $url=Yii::app()->baseUrl."/img/noimage.jpg";                
            return CHtml::image($url,'No Image');
        }
    }
}
From Image Folder

// From Image Folder
public function showproof_from_image_folder(){
    if(isset($this->vproof_id) && $this->vproof_id!=''){
        $imgurl=$this->vproof->path;
        $imgurl=Yii::app()->baseUrl."/".$imgurl;
        $imgurl_path=Yii::app()->basePath."/../".$this->vproof->path;
        if(file_exists($imgurl_path)){
            return "<a target='_blank' href='".$imgurl."'>
            <img src='".$imgurl."' width='100px' height='100px' />
            </a>";
        }
    }
    return "NotSet";
}
?>