Resize Dan Upload Image

Selamat siang gan,

Kali ini mau numpang sharing resize dan upload file. Intinya kita punya foto asli (>2Mb), gimana kita buat aplikasi upload foto image yg gak perlu olah dulu manual foto tsb.

Saya kebetulan udah impplementasi ekstensi imagedan udah dicoba di beberapa aplikasi saya contohnya merah-putih.

Proses step-by-stepnya sbb:

  1. Download ekstension image di alamat image.

  2. Esktrak folder /image dan letakkan di /protected/extentions

  3. edit /protected/config/main.php




'components'=>array(

..

                //utk resize image

                'image'=>array(     

                'class'=>'application.extensions.image.CImageComponent',            

                'driver'=>'GD', 

                ) ,

..



  1. Utk ukuran max file yg bisa diupload aturnya di dua tempat:

a. php.ini file (klo di web server biasany ada di dir /etc) tambahkan:

upload_max_filesize = 5M

b. di model nya protected/model/News.php:




..

public function rules()

	{

		return array(

                        ..

			array('foto', 'file', 'allowEmpty'=>true,'maxSize'=>1024*1024*5, //ukuran file max 

                             'types'=>'jpg,jpeg,png','tooLarge'=>'Ukuran foto tidak lebih dari 5Mb',

                             'wrongType'=>'Jenis file hanya JPEG atau PNG',

                             'on'=>'insert'),

			array('foto', 'file', 'allowEmpty'=>true,'maxSize'=>1024*1024*5, 

                             'types'=>'jpg,jpeg,png','tooLarge'=>'Ukuran foto tidak lebih dari 5Mb',

                             'wrongType'=>'Jenis file hanya JPEG atau PNG',

                             'except'=>'insert'),

                        ...

                         // The following rule is used by search().

			// Please remove those attributes that should not be searched.

			array('id, judul, jenis, isi, foto, video, inputer, time', 'safe', 'on'=>'search'),

		);

	}

..



  1. Sedangkan untuk controller protected/controllers/NewsController.php:



...

        public function actionCreate()

	{

		$model=new News;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);

             

		if(isset($_POST['News']))

		{

                            $rnd = rand(0,9999);  // generate random number between 0-9999

                            $model->attributes=$_POST['News'];

 

                            $uploadedFile=CUploadedFile::getInstance($model,'foto');

                        //  if(!empty($model->foto))

                          if(!empty($uploadedFile))

                           { 

                              $fileName = "{$rnd}-{$uploadedFile}";  // random number + file name

                              $var = 'http://merahputih.panjattebing.org'; 

                              $model->foto = $var.'/images/data/'.$fileName;

                              $model->save(); //mengirim data lokasi file foto ke mysql

                               

                              //$uploadedFile->saveAs(Yii::app()->basePath.'/../images/data/'.$fileName);  

                              //simpan file 

                              $name=Yii::app()->basePath.'/../images/data/'.$fileName;

                              $uploadedFile->saveAs($name);  //

                              //

                              //utk resize gambar

                              $image = Yii::app()->image->load($name);


                              /* begin- utk memutar jika file asli portrait */

                              $tinggi=$image->__get('height');

                              $lebar=$image->__get('width');

                              if($tinggi>$lebar)

                              {

                              $image->resize(600, 400)->rotate(0);

                              }

                              else

                              {

                              $image->resize(600, 400);

                              }

                              /* end- utk memutar jika file ori portrait */


                              $image->save();

                              

                              $this->redirect(array('admin'));

                             }

                            else

                             {

                                 $model->save();

                                 $this->redirect(array('admin')); //new

                             }

                  }

                  

                $this->render('create',array(

			 'model'=>$model,

		));

	}




	public function actionUpdate($id)

	{

		$model=$this->loadModel($id);


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['News']))

                {

                 $_POST['News']['foto'] = $model->foto;

                 $model->attributes=$_POST['News'];

            

                 $uploadedFile=CUploadedFile::getInstance($model,'foto');

                 //proses simpan file gambar

                 if(!empty($uploadedFile))

                           { 

                              $rnd = rand(0,9999);  // generate random number between 0-9999

                              $var = 'http://merahputih.panjattebing.org'; 

                              $fileName = "{$rnd}-{$uploadedFile}";  // random number + file name

                              $model->foto = $var.'/images/data/'.$fileName ;

                              $model->save(); //mengirim data lokasi file foto ke mysql


                              //simpan file 

                              

                              $name=Yii::app()->basePath.'/../images/data/'.$fileName;

                              $uploadedFile->saveAs($name);  //

                              //

                              //utk resize gambar

                              $image = Yii::app()->image->load($name);


                              /* begin- utk memutar jika file ori portrait */

                              $tinggi=$image->__get('height');

                              $lebar=$image->__get('width');

                              if($tinggi>$lebar)

                              {

                              $image->resize(600, 400)->rotate(0);

                              }

                              else

                              {

                              $image->resize(600, 400);

                              }

                              /* end- utk memutar jika file ori portrait */


                              $image->save();

                              

                              $this->redirect(array('view','id'=>$model->id));

                             }

                             else

                             {

                                 $model->save();

                                 $this->redirect(array('view','id'=>$model->id));

                             }

                    }    

                    $this->render('update',array(

			 'model'=>$model,

		));

	}

..



6.Form uploadnya sbb:

a. Jangan lupa menambahkan ‘enctype’ => ‘multipart/form-data’,), di awal atas form kongkritnya:




<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'news-form',

	'enableAjaxValidation'=>false,

        'htmlOptions' => array(

        'enctype' => 'multipart/form-data', //tambahan dari _form hasil gii

    ),

)); ?>



b. lalu ketik bagian ini di form nya:




        <div class="row">

                <?php echo $form->labelEx($model,'foto'); ?>

                <?php echo CHtml::activeFileField($model, 'foto'); ?>  <font color='orange'><=.jpg/.png dan pastikan ukuran file max 5Mb</font>

                <?php echo $form->error($model,'foto'); ?>

        </div>

<?php if($model->isNewRecord!='1'){ ?>

<div class="row">

     <?php echo CHtml::image($model->foto,"foto",array("width"=>100)); ?>  

</div>

<?php

}

?>



  1. pastikan tabel MySql kita ada field foto dengan tipe varchar size 250 default NULL.

  2. buat sub-directory /data utk menyimpan file foto di dalam dir /images. Pastikan direktory tempat menyimpan (images/data) itu mempunyai permission mode: 775 (gunakan perintah Set permission).

  3. Skrg waktu mencoba…jika tidak ada halangan di field foto tabel mysql akan ada detil lengkap nama file yg diupload.

  4. Untuk menampilkan di _view.php:




<?php


if(!empty($data->foto)){ //jika record foto nya tidak kosong

    echo CHtml::image(Yii::app()->request->baseUrl.$data->foto,"Image-".$data->id,array("width"=>40,"height"=>40)); 

}

?>



Untuk tampil di view.php:




if(!empty($model->foto))

{ 

    echo CHtml::image(Yii::app()->request->baseUrl.$model->foto,"Image".$model->id,array("width"=>320)); 

}



  1. That’s it…semoga berhasil ya.

Salam hangat, MH

Makasih agan M Hermansyah telah bersedia meluangkan waktu untuk berbagi di sini. Cendol sent. :)

Sekadar saran konstruktif saja, ya: mungkin lain kali untuk penulisan kodenya bisa diberi tag khusus untuk kode dan indentasi yang lebih baik?


Masukkan kode di sini ....

Sekali lagi terima kasih atas sharing-nya. Ditunggu tutorial-tutorial berikutnya. :lol:

thx masukannya…skrg tampilan sdh dibuat cantik…

Hi, thanks for the great tutorial on how to upload photo. But, I have the problem of uploading the photo. I follow the instructions that u posted earlier but it returns an error ‘[color="#FF0000"]move_uploaded_file(C:\xampp\htdocs\test\protected/../images/data/{$rnd}-{$uploadedFile}): failed to open stream: No such file or directory[/color]’.

Any ideas how to solve it? Thanks in advance.

Here’s my code:

controller




public function actionCreate()

	{

		$model=new Student;

		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['Student']))

		{

		    $rnd = rand(0,9999);  // generate random number between 0-9999

			$model->attributes=$_POST['Student'];

			$uploadedFile=CUploadedFile::getInstance($model,'foto');

			

			if(!empty($uploadedFile))

                           { 

                              $fileName = "{$rnd}-{$uploadedFile}";  // random number + file name

                              $var = 'http://merahputih.panjattebing.org'; 

                              $model->foto = $var.'/images/data/'.$fileName;

                              $model->save(); //mengirim data lokasi file foto ke mysql

                               

                              //$uploadedFile->saveAs(Yii::app()->basePath.'/../images/data/'.$fileName);  

                              //simpan file 

                              $name=Yii::app()->basePath.'/../images/data/'.$fileName;

                              $uploadedFile->saveAs($name);  //

                              //

                              //utk resize gambar

                              $image = Yii::app()->image->load($name);


                              /* begin- utk memutar jika file asli portrait */

                              $tinggi=$image->__get('height');

                              $lebar=$image->__get('width');

                              if($tinggi>$lebar)

                              {

                              $image->resize(600, 400)->rotate(0);

                              }

                              else

                              {

                              $image->resize(600, 400);

                              }

                              /* end- utk memutar jika file ori portrait */


                              $image->save();

                              

                              $this->redirect(array('view','id'=>$model->id));;

                             }

                            else

                             {

                                 $model->save();

                                 $this->redirect(array('view','id'=>$model->id)); //new

                             }

			

		}


		$this->render('create',array(

			'model'=>$model,

		));

	}



model




public function rules()

	{

		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		return array(

			array('username, password, programme, intake, email, contact', 'required'),

			array('contact', 'numerical', 'integerOnly'=>true),

			array('username', 'length', 'max'=>10),

			array('password, programme, intake', 'length', 'max'=>20),

			array('email', 'length', 'max'=>50),

			array('foto', 'file', 'allowEmpty'=>true,'maxSize'=>1024*1024*5, //ukuran file max 

                             'types'=>'jpg,jpeg,png','tooLarge'=>'Ukuran foto tidak lebih dari 5Mb',

                             'wrongType'=>'Jenis file hanya JPEG atau PNG',

                             'on'=>'insert'),

            array('foto', 'file', 'allowEmpty'=>true,'maxSize'=>1024*1024*5, 

                             'types'=>'jpg,jpeg,png','tooLarge'=>'Ukuran foto tidak lebih dari 5Mb',

                             'wrongType'=>'Jenis file hanya JPEG atau PNG',

                             'except'=>'insert'),


			// The following rule is used by search().

			// @todo Please remove those attributes that should not be searched.

			array('id, username, password, programme, intake, email, contact', 'safe', 'on'=>'search'),

		);

	}



view




<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'student-form',

	'enableAjaxValidation'=>false,

	'htmlOptions' => array(

        'enctype' => 'multipart/form-data', //tambahan dari _form hasil gii

    ),


)); ?>


	<p class="note">Fields with <span class="required">*</span> are required.</p>


	<?php echo $form->errorSummary($model); ?>

    

	 <div class="row">

                <?php echo $form->labelEx($model,'foto'); ?>

                <?php echo CHtml::activeFileField($model, 'foto'); ?>  <font color='orange'><=.jpg/.png dan pastikan ukuran file max 5Mb</font>

                <?php echo $form->error($model,'foto'); ?>

     </div>

      <?php if($model->isNewRecord!='1'){ ?>

     <div class="row">

     <?php echo CHtml::image($model->foto,"foto",array("width"=>100)); ?>  

     </div>

     <?php } ?>

	

	<div class="row">

		<?php echo $form->labelEx($model,'username'); ?>

		<?php echo $form->textField($model,'username',array('size'=>10,'maxlength'=>10)); ?>

		<?php echo $form->error($model,'username'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'password'); ?>

		<?php echo $form->passwordField($model,'password',array('size'=>20,'maxlength'=>20)); ?>

		<?php echo $form->error($model,'password'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'programme'); ?>

		<?php echo $form->dropDownList($model,'programme', CHtml::listData(Programme::model()->findAll(), 'programme', 'programme'), array('empty'=>'---Select Programme---'));?>

		<?php echo $form->error($model,'programme'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'intake'); ?>

		<?php echo $form->textField($model,'intake',array('size'=>20,'maxlength'=>20)); ?>

		<?php echo $form->error($model,'intake'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'email'); ?>

		<?php echo $form->textField($model,'email',array('size'=>50,'maxlength'=>50)); ?>

		<?php echo $form->error($model,'email'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'contact'); ?>

		<?php echo $form->textField($model,'contact'); ?>

		<?php echo $form->error($model,'contact'); ?>

	</div>


	<div class="row buttons">

		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

	</div>


<?php $this->endWidget(); ?>



Hi,

Sorry for late in reply…

I’am so busy and rare to login to my yiiframework account. next better to try to direct message.

Seem your problem are:

  1. you did not have created directory /data within /images (default created by yii). ensure you have change directory permission. if you have done, try to change (sorry i little forget):



 $name=Yii::app()->basePath.'/../images/data/'.$fileName;



to be




 $name=Yii::app()->basePath.'../images/data/'.$fileName;



or




 $name=Yii::app()->basePath.'./images/data/'.$fileName;



or




 $name=Yii::app()->basePath.'/images/data/'.$fileName;



and do not forget to change




$var = 'http://merahputih.panjattebing.org';



to your own web address. otherwise when view look for the image file can not find it.

Hope the above could assist you