画像のサイズ設定用ファイルを用意します。
/app/config/app.php
<?php
define('PIC_WIDTH', 100);
define('PIC_HEIGHT', 100);
?>
続いて、コントローラーの設定をします。
/app/controllers/samples_controller.php
//設定ファイルの追加
config('app');
class SamplesController extends AppController
{
//登録
function add()
{
if(!empty($this->data))
{
//画像アップ
if (!empty($this->data['Sample']['pic']['name'])) {
$tmp_file = $this->data['Sample']['pic']['tmp_name'];
$imginfo = getimagesize($tmp_file);
clearstatcache();
//300KB、JPEG・GIF・PNG
if (filesize($tmp_file)>300000 || ($imginfo[2] < 1 || $imginfo[2] > 3)) { $this->set('file_error',true); return false; }
$upload_path = WWW_ROOT . "img/sample" . DS;
$width_old = $imginfo[0];
$height_old = $imginfo[1];
$width_new = PIC_WIDTH;
$height_new = PIC_HEIGHT;
switch ($imginfo[2]) {
case 2: // jpeg
$filename = sprintf("%04d%02d%02d%02d%02d%02d.jpg",date("Y"),date("m"),date("d"),date("H"),date("i"),date("s"));
$jpeg = imagecreatefromjpeg($tmp_file);
$jpeg_new = imagecreatetruecolor($width_new, $height_new);
imagecopyresampled($jpeg_new,$jpeg,0,0,0,0,$width_new,$height_new,$width_old,$height_old);
imagejpeg($jpeg_new, $upload_path . $filename, 100);
break;
case 1: // gif
$filename = sprintf("%04d%02d%02d%02d%02d%02d.jpg",date("Y"),date("m"),date("d"),date("H"),date("i"),date("s"));
$gif = imagecreatefromgif($tmp_file);
$gif_new = imagecreatetruecolor($width_new, $height_new);
imagecopyresampled($gif_new,$gif,0,0,0,0,$width_new,$height_new,$width_old,$height_old);
imagegif($gif_new, $upload_path . $filename, 100);
break;
case 3: // png
$filename = sprintf("%04d%02d%02d%02d%02d%02d.jpg",date("Y"),date("m"),date("d"),date("H"),date("i"),date("s"));
$png = imagecreatefrompng($tmp_file);
$png_new = imagecreatetruecolor($width_new, $height_new);
imagecopyresampled($png_new,$png,0,0,0,0,$width_new,$height_new,$width_old,$height_old);
imagepng($png_new, $upload_path . $filename, 100);
break;
Default:
break;
}
$this->data['Sample']['pic'] = $filename;
} else {
$this->data['Sample']['pic'] = "";
}
if($this->Sample->save($this->data))
{
$this->redirect('/samples');
}
}
}
}
?>
ビューも下記の内容を追加します。
/app/views/samples/add.thtml
<form method="post" action="<?php echo $html->url('/samples/add') ?>" enctype="multipart/form-data">
:
:
<label for="SampleImage">画像</label>
<?= $html->file('Sample/pic'); ?><br>
参考サイト:画像アップロード処理のセキュリティホールをふさぐ(CakePHP修行 #37) | i d e a * i d e a
コントローラ
