<?php

class WaterMarkModel extends CFormModel
{
    public $serverFile;
}

class WaterMarkController extends AdminController
{

    public function actionIndex()
    {
        $model = new WaterMarkModel();
        if (isset($_POST['WaterMarkModel'])) {
            $model->setAttributes($_POST['WaterMarkModel'], false);
            foreach ($model->serverFile as $imagePath) {
                $imagePath = substr($imagePath, 1);
                $image_info = getimagesize($imagePath);
                $imageType = $image_info[2];
                $create = null;
                $save = null;
                switch ($imageType) {
                    case IMAGETYPE_JPEG:
                        $create = 'imagecreatefromjpeg';
                        $save = 'imagejpeg';
                        break;
                    case IMAGETYPE_GIF:
                        $create = 'imagecreatefromgif';
                        $save = 'imagegif';
                        break;
                    case IMAGETYPE_PNG:
                        $create = 'imagecreatefrompng';
                        $save = 'imagepng';
                        break;
                }

                $path = 'images/watermark.png';
                if (!isset($create)) continue;
                $mark = imagecreatefrompng($path);
                $image = $create($imagePath);
                $x = 0;
                $y = 0;
                $w = round(imagesx($mark) * imagesx($image) / 800);
                $h = round(imagesy($mark) * imagesx($image) / 800);

                imagealphablending($image, true);
                imagesavealpha($image, true);

                imagecopyresampled($image, $mark, $x, $y, 0, 0, $w, $h, imagesx($mark), imagesy($mark));
                imagedestroy($mark);
                $save($image, $imagePath);
            }
            Yii::app()->user->setFlash('images', $model->serverFile);
        }
        $this->render('index', array('model' => $model));
    }
}
