Upload and Resize Image In CodeIgniter

I am having some trouble in image upload and resizing it in CodeIgniter. So I am finally overcome some of the area of it. And now sharing it with all of those who having the same problem.

Please also help me if I was wrong or you have a good example beyond this.

First you must load “image_lib” library of CI.

This is a controller in CI

  

public function imageUpload()
    {
        $data = array();
        if ($this->input->post('submit'))
        {
            if ($_FILES["sc_name"]["name"])
            {
                $path = './upload_image';
                if (!is_dir($path))
                    mkdir($path, 0755);

                $pathMain = './upload_image/source';
                if (!is_dir($pathMain))
                    mkdir($pathMain, 0755);

                $pathThumb = './upload_image/100X100';
                if (!is_dir($pathThumb))
                    mkdir($pathThumb, 0755);

                $path2Thumb = './upload_image/200X200';
                if (!is_dir($path2Thumb))
                    mkdir($path2Thumb, 0755);

                $path3Thumb = './upload_image/300X300';
                if (!is_dir($path3Thumb))
                    mkdir($path3Thumb, 0755);

                $path4Thumb = './upload_image/400X400';
                if (!is_dir($path4Thumb))
                    mkdir($path4Thumb, 0755);

                $result = $this->do_upload("sc_name", $pathMain);

                if (!$result['status'])
                    $data['error_msg'] ="Can not upload Image for " . $result['error'] . " ";
                else
                {
                    $pathThumb = './upload_image/100X100';
                    if (!is_dir($pathThumb))
                        mkdir($pathThumb, 0755);

                    //in other folder
                    if($this->resize_image($pathMain . '/' . $result['upload_data']['file_name'], $pathThumb . '/'.time().'100X100.gif','100','100'))
                        echo 'Image 100X100 resize done';
                    else
                        echo 'Image 100X100 resize failed';
                     if($this->resize_image($pathMain . '/' . $result['upload_data']['file_name'], $path2Thumb . '/'.time().'200X200.gif','200','200'))
                        echo 'Image 200X200 resize done';
                    else
                        echo 'Image 200X200 resize failed';
                     if($this->resize_image($pathMain . '/' . $result['upload_data']['file_name'], $path3Thumb . '/'.time().'300X300.gif','300','300'))
                        echo 'Image 300X300 resize done';
                    else
                        echo 'Image 300X300 resize failed';

                    //in same folder

                     if($this->resize_image($pathMain . '/' . $result['upload_data']['file_name'], time().'100X100.gif','100','100'))
                        echo 'Image 100X100 Same Folder resize done';
                    else
                        echo 'Image 100X100 Same Folder resize failed';
                     if($this->resize_image($pathMain . '/' . $result['upload_data']['file_name'], time().'200X200.gif','200','200'))
                        echo 'Image 200X200 Same Folder resize done';
                    else
                        echo 'Image 200X200 Same Folder resize failed';
                     if($this->resize_image($pathMain . '/' . $result['upload_data']['file_name'], time().'300X300.gif','300','300'))
                        echo 'Image 300X300 Same Folder resize done';
                    else
                        echo 'Image 300X300 Same Folder resize failed';

                }
            }
        }

        $this->load->view('sc/upload_image', $data);
    }

Upload Function inside the CI Controller


function do_upload($htmlFieldName, $path)
    {
        $config['file_name'] = time();
        $config['upload_path'] = $path;
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '2000';
        $config['max_width'] = '2000';
        $config['max_height'] = '2000';
        $this->load->library('upload', $config);
        $this->upload->initialize($config);
        unset($config);
        if (!$this->upload->do_upload($htmlFieldName))
        {
            return array('error' => $this->upload->display_errors(), 'status' => 0);
        } else
        {
            return array('status' => 1, 'upload_data' => $this->upload->data());
        }
    }

Resize Function inside the CI Controller


function resize_image($sourcePath, $desPath, $width = '500', $height = '500')
    {
        $this->image_lib->clear();
        $config['image_library'] = 'gd2';
        $config['source_image'] = $sourcePath;
        $config['new_image'] = $desPath;
        $config['quality'] = '100%';
        $config['create_thumb'] = TRUE;
        $config['maintain_ratio'] = true;
        $config['thumb_marker'] = '';
        $config['width'] = $width;
        $config['height'] = $height;
        $this->image_lib->initialize($config);

        if ($this->image_lib->resize())
            return true;
        return false;
    }

And Finally The form

<?php echo form_open_multipart() ?>

<label for="sc_name">Name</label>
<input type="file" name="sc_name" /><br />
<input type="submit" name="submit" value="Create" />

Advertisements

Generate Order Number

That’s what I’ll do. As for formatting the number, here’s what I did…

$id_num = 5;
$order_num = sprintf("NSC-%010d", $id_num);
echo $order_num;

That gives me a number like…

NSC-0000000005

So if the $id_num is 2044 then the zero spaces will account for the larger id number and give me…

NSC-0000002044

Figured I’d post it, in case anyone else needed something similar. Thanks again!

Thanks to wilhud

Remove index.php from CI

Hi,
I am previously fail to do this. But Now I am success.
big thanks to CI forums for helping me out.

You just need to create a .htaccess in your root and use these codes

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]  

Hope this will help someone.

Thanks.

Fource to download a file in php as well as in joomla 2.5

I am wondering how to download forcefully a file using php
I am using this code. If any one has more better code please share with us

           $filename = $path . DS . $this->item->file;die();
            if (is_file($path . DS . $this->item->file))
            {
                if (file_exists($filename))
                {
                    header('Content-Description: File Transfer');
                    header('Content-Type: application/octet-stream');
                    header('Content-Disposition: attachment; filename=' . basename($filename));
                    header('Content-Transfer-Encoding: binary');
                    header('Expires: 0');
                    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                    header('Pragma: public');
                    header('Content-Length: ' . filesize($filename));
                    ob_clean();
                    flush();
                    readfile($filename);
                    exit;
                }
            }

Here file path will be like as D:\xampp\htdocs\jm-dmrd\file\noticeboard\pdf\New_Microsoft_Word_Document-.docx

Thanks

How to delete blank lines from code in Netbeans

Formatting in Netbeans will not delete all the blank lines and sometimes we want this. For example, when the charset is messed up and the blank spaces are doubled because CR and LF – Unix – Windows compatibility.

Solution: Ctrl-F (find) in Netbeans as Regular Expression:

\n\s*(\n)

and Replace All by

$1

A special thanks to http://seo.911web.org/netbeans-how-to-delete-blank-lines

Image resize in php

Here there are some basic help for image resizing code in php


function get_width($mages) {
    list($img_width, $img_height) = getimagesize($mages);
    return $img_width;
}

function get_height($mages) {
    list($img_width, $img_height) = getimagesize($mages);
    return $img_height;
}

function get_ratio($mages) {
    list($img_width, $img_height) = getimagesize($mages);
    return $img_width / $img_height;
}

function get_type($mages) {
    list($img_width, $img_height, $type, $attr) = getimagesize($mages);
    return $type;
}

function get_mime($mages) {
    $array = getimagesize($mages);
    return $array['mime'];
}

function resize($width, $height, $img) {

    $old_image = imagecreatefromjpeg($img);
    $image_width = imagesx($old_image);
    $image_height = imagesy($old_image);
    $image_aspect_ratio = $image_width / $image_height;
    $image_type = get_type($img);
    $image_mime = get_mime($img);

    $new_image = imagecreatetruecolor($width, $height);
    imagecopyresampled($new_image, $old_image, 0, 0, 0, 0, $width, $height, $image_width, $image_height);
    if(file_exists('resized-imges/sample2.jpg'))
        unlink('resized-imges/sample2.jpg');
    imagejpeg($new_image, 'resized-imges/sample2.jpg', 100);

    imagedestroy($new_image);
}

function resizeToHeight($height, $img) {

    $old_image = imagecreatefromjpeg($img);
    $image_width = imagesx($old_image);
    $image_height = imagesy($old_image);
    $ratio = $height / $image_height;
    $width = $image_width * $ratio;
    resize($width, $height, $img);
}

function resizeToWidth($width, $img) {
    $old_image = imagecreatefromjpeg($img);
    $image_width = imagesx($old_image);
    $image_height = imagesy($old_image);
    $ratio = $width / $image_width;
    $height = $image_height * $ratio;
    resize($width, $height, $img);
}

$img = ('images/Shrek2-3.jpg');

resizeToWidth(600, $img);

Profile preview in social engine like facebook

If any one need to preview a user profile then he/she might look here.

At first I make a controller in user module. It is similar to profile view. I simply want to load this page where the viewer will be null. So I make some adjustment.
#step 1:
Create a controller just for keep it simple

<?php
class User_PreviewProfileController extends Core_Controller_Action_Standard
{

    public function init()
    {
        // @todo this may not work with some of the content stuff in here, double-check
        $subject = null;
        if (!Engine_Api::_()->core()->hasSubject())
        {
            $id = $this->_getParam('id');

            // use viewer ID if not specified
            //if( is_null($id) )
            //  $id = Engine_Api::_()->user()->getViewer()->getIdentity();

            if (null !== $id)
            {
                $subject = Engine_Api::_()->user()->getUser($id);
                if ($subject->getIdentity())
                {
                    Engine_Api::_()->core()->setSubject($subject);
                }
            }
        }

        $this->_helper->requireSubject('user');
        $this->_helper->requireAuth()->setNoForward()->setAuthParams(
                $subject, Engine_Api::_()->user()->getViewer(), 'view'
        );
    }

    public function indexAction()
    {
        Engine_Api::_()->user()->setViewer();
        $subject = Engine_Api::_()->core()->getSubject();
        $viewer = Engine_Api::_()->user()->getViewer();
        // check if the viewer of this page is the same user
        if ($subject->isSelf($viewer))
        {
            $viewer = Engine_Api::_()->user()->getViewer($viewer->getIdentity());
        }
        


        // check public settings
        $require_check = Engine_Api::_()->getApi('settings', 'core')->core_general_profile;
        if (!$require_check && !$this->_helper->requireUser()->isValid())
        {
            return;
        }

        // Check enabled
        if (!$subject->enabled && !$viewer->isAdmin())
        {
            return $this->_forward('requireauth', 'error', 'core');
        }

        // Check block
        if ($viewer->isBlockedBy($subject) && !$viewer->isAdmin())
        {
            return $this->_forward('requireauth', 'error', 'core');
        }

        // Increment view count
        if (!$subject->isSelf($viewer))
        {
            $subject->view_count++;
            $subject->save();
        }


        // Check to see if profile styles is allowed
        $style_perm = Engine_Api::_()->getDbtable('permissions', 'authorization')->getAllowed('user', $subject->level_id, 'style');
        if ($style_perm)
        {
            // Get styles
            $table = Engine_Api::_()->getDbtable('styles', 'core');
            $select = $table->select()
                    ->where('type = ?', $subject->getType())
                    ->where('id = ?', $subject->getIdentity())
                    ->limit();

            $row = $table->fetchRow($select);
            if (null !== $row && !empty($row->style))
            {
                $this->view->headStyle()->appendStyle($row->style);
            }
        }

        // Render
        $this->_helper->content
                ->setNoRender()
                ->setEnabled()
        ;
    }

}

#Step 2
router for the link

// User - Specific Profile Preview
        'user_preview_profile' => array(
            'route' => 'preview/profile/:id/*',
            'defaults' => array(
                'module' => 'user',
                'controller' => 'preview-profile',
                'action' => 'index'
            )
        ),

#step 3
create page for the link

INSERT INTO `engine4_core_pages` (`name`, `displayname`, `url`, `title`, `description`, `keywords`, `custom`, `fragment`, `layout`, `levels`, `provides`, `view_count`) VALUES
('user_preview-profile_index', 'Preview Member Profile', NULL, 'Preview Member Profile', 'This is a member''s preview profile.', '', 0, 0, '', NULL, 'subject=user', 0);

#step 4
Now create content of the page

INSERT INTO `engine4_core_content` (`content_id`, `page_id`, `type`, `name`, `parent_content_id`, `order`, `params`, `attribs`) VALUES
(609, 18, 'container', 'main', NULL, 2, '[""]', NULL),
(610, 18, 'container', 'left', 609, 4, '[""]', NULL),
(611, 18, 'container', 'middle', 609, 6, '[""]', NULL),

Note: Here content_id for main remain empty when you create main
for other put main content_id as parent_content_id

And then do same as member profile does.

#step 5
Slight change to your getViewer model function

// Viewer

    /**
     * Gets the current viewer instance using the authentication storage
     *
     * @return User_Model_User
     */
    public function getViewer($id = null)
    {
        if (null === $this->_viewer)
        {
            $identity = $this->getAuth()->getIdentity();
            $this->_viewer = $this->_getUser($identity);
        }
        elseif($this->getAuth()->getIdentity() == $id)
        {
            $this->_viewer = $this->_getUser(null);
        }

        return $this->_viewer;
    }

#step 6
Now create a new menu in user home menu

INSERT INTO `engine4_core_menuitems` (`name`, `module`, `label`, `plugin`, `params`, `menu`, `submenu`, `enabled`, `custom`, `order`) VALUES
('user_home_preview', 'user', 'Preview My Profile', 'User_Plugin_Menus', '{"route":"user_preview_profile","icon":"application/modules/User/externals/images/links/profile.png"}', 'user_home', '', 1, 0, 22);

#step 7
create a initialization function for the menu in user core

public function onMenuInitialize_UserHomePreview($row)
  {
    $viewer = Engine_Api::_()->user()->getViewer();
    if( $viewer->getIdentity() ) {
      return array(
        'label' => $row->label,
        'icon' => $row->params['icon'],
        'route' => 'user_preview_profile',
        'params' => array(
          'id' => $viewer->getIdentity()
        )
      );
    }
    return false;
  }

That’s it. Have fun!

%d bloggers like this: