This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details: http://www.gnu.org/licenses/gpl.html
Ejemplo n.º 1
1
 function imageDualResize($filename, $cleanFilename, $wtarget, $htarget)
 {
     if (!file_exists($cleanFilename)) {
         $dims = getimagesize($filename);
         $width = $dims[0];
         $height = $dims[1];
         while ($width > $wtarget || $height > $htarget) {
             if ($width > $wtarget) {
                 $percentage = $wtarget / $width;
             }
             if ($height > $htarget) {
                 $percentage = $htarget / $height;
             }
             /*if($width > $height)
             		{
             			$percentage = ($target / $width);
             		}
             		else
             		{
             			$percentage = ($target / $height);
             		}*/
             //gets the new value and applies the percentage, then rounds the value
             $width = round($width * $percentage);
             $height = round($height * $percentage);
         }
         $image = new SimpleImage();
         $image->load($filename);
         $image->resize($width, $height);
         $image->save($cleanFilename);
         $image = null;
     }
     //returns the new sizes in html image tag format...this is so you can plug this function inside an image tag and just get the
     return "src=\"{$baseurl}/{$cleanFilename}\"";
 }
Ejemplo n.º 2
0
function upload_imagem_unica($pasta_upload, $novo_tamanho_imagem, $novo_tamanho_imagem_miniatura, $host_retorno, $upload_miniatura)
{
    // data atual
    $data_atual = data_atual();
    // array com fotos
    $fotos = $_FILES['foto'];
    // extensoes de imagens disponiveis
    $extensoes_disponiveis[] = ".jpeg";
    $extensoes_disponiveis[] = ".jpg";
    $extensoes_disponiveis[] = ".png";
    $extensoes_disponiveis[] = ".gif";
    $extensoes_disponiveis[] = ".bmp";
    // nome imagem
    $nome_imagem = $fotos['tmp_name'];
    $nome_imagem_real = $fotos['name'];
    // dimensoes da imagem
    $image_info = getimagesize($_FILES["foto"]["tmp_name"]);
    $largura_imagem = $image_info[0];
    $altura_imagem = $image_info[1];
    // extencao
    $extensao_imagem = "." . strtolower(pathinfo($nome_imagem_real, PATHINFO_EXTENSION));
    // nome final de imagem
    $nome_imagem_final = md5($nome_imagem_real . $data_atual) . $extensao_imagem;
    $nome_imagem_final_miniatura = md5($nome_imagem_real . $data_atual . $data_atual) . $extensao_imagem;
    // endereco final de imagem
    $endereco_final_salvar_imagem = $pasta_upload . $nome_imagem_final;
    $endereco_final_salvar_imagem_miniatura = $pasta_upload . $nome_imagem_final_miniatura;
    // informa se a extensao de imagem e permitida
    $extensao_permitida = retorne_elemento_array_existe($extensoes_disponiveis, $extensao_imagem);
    // se nome for valido entao faz upload
    if ($nome_imagem != null and $nome_imagem_real != null and $extensao_permitida == true) {
        // upload de imagem normal
        $image = new SimpleImage();
        $image->load($nome_imagem);
        // aplica escala
        if ($largura_imagem > $novo_tamanho_imagem) {
            $image->resizeToWidth($novo_tamanho_imagem);
        }
        // salva a imagem grande
        $image->save($endereco_final_salvar_imagem);
        // upload de miniatura
        if ($upload_miniatura == true) {
            $image = new SimpleImage();
            $image->load($nome_imagem);
            // modo de redimencionar
            if ($largura_imagem > $novo_tamanho_imagem_miniatura) {
                $image->resizeToWidth($novo_tamanho_imagem_miniatura);
            }
            // salva a imagem em miniatura
            $image->save($endereco_final_salvar_imagem_miniatura);
        }
        // array de retorno
        $retorno['normal'] = $host_retorno . $nome_imagem_final;
        $retorno['miniatura'] = $host_retorno . $nome_imagem_final_miniatura;
        $retorno['normal_root'] = $endereco_final_salvar_imagem;
        $retorno['miniatura_root'] = $endereco_final_salvar_imagem_miniatura;
        // retorno
        return $retorno;
    }
}
 /**
  * 上传图片
  */
 public function actionUpload()
 {
     $fn = $_GET['CKEditorFuncNum'];
     $url = WaveCommon::getCompleteUrl();
     $imgTypeArr = WaveCommon::getImageTypes();
     if (!in_array($_FILES['upload']['type'], $imgTypeArr)) {
         echo '<script type="text/javascript">
             window.parent.CKEDITOR.tools.callFunction("' . $fn . '","","图片格式错误!");
             </script>';
     } else {
         $projectPath = Wave::app()->projectPath;
         $uploadPath = $projectPath . 'data/uploadfile/substance';
         if (!is_dir($uploadPath)) {
             mkdir($uploadPath, 0777);
         }
         $ym = WaveCommon::getYearMonth();
         $uploadPath .= '/' . $ym;
         if (!is_dir($uploadPath)) {
             mkdir($uploadPath, 0777);
         }
         $imgType = strtolower(substr(strrchr($_FILES['upload']['name'], '.'), 1));
         $imageName = time() . '_' . rand() . '.' . $imgType;
         $file_abso = $url . '/data/uploadfile/substance/' . $ym . '/' . $imageName;
         $SimpleImage = new SimpleImage();
         $SimpleImage->load($_FILES['upload']['tmp_name']);
         $SimpleImage->resizeToWidth(800);
         $SimpleImage->save($uploadPath . '/' . $imageName);
         echo '<script type="text/javascript">
             window.parent.CKEDITOR.tools.callFunction("' . $fn . '","' . $file_abso . '","上传成功");
             </script>';
     }
 }
Ejemplo n.º 4
0
 protected function uploadFile()
 {
     if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $this->path)) {
         $path = $this->path;
         if (!$this->db->query("INSERT photo (name,folder,time,status) \n\t\t\tVALUES ('" . $this->name . "','" . $this->folder . "','" . time() . "','temp')")) {
             die("error");
         }
         $id = $this->db->getLastId();
         $this->image->load($path);
         $full = new SimpleImage();
         $full->load($path);
         if ($full->getWidth() > 1200) {
             $full->resizeToWidth(1200);
         }
         $full->save(str_replace('.', '.full.', $path));
         if ($this->image->getWidth() > 600) {
             $this->image->resizeToWidth(600);
         }
         $this->image->save($path);
         $size = $this->f->getFullSize($path, 90, 90);
         $img = array('name' => $this->name, 'path' => $path, 'count' => $this->getNum(), 'width' => $size['width'], 'height' => $size['height'], 'id' => $id);
         echo json_encode($img);
     } else {
         echo "error";
     }
 }
Ejemplo n.º 5
0
function processScreenshots($gameID)
{
    ## Select all fanart rows for the requested game id
    $ssResult = mysql_query(" SELECT filename FROM banners WHERE keyvalue = {$gameID} AND keytype = 'screenshot' ORDER BY filename ASC ");
    ## Process each fanart row incrementally
    while ($ssRow = mysql_fetch_assoc($ssResult)) {
        ## Construct file names
        $ssOriginal = $ssRow['filename'];
        $ssThumb = "screenshots/thumb" . str_replace("screenshots", "", $ssRow['filename']);
        ## Check to see if the original fanart file actually exists before attempting to process
        if (file_exists("../banners/{$ssOriginal}")) {
            ## Check if thumb already exists
            if (!file_exists("../banners/{$ssThumb}")) {
                ## If thumb is non-existant then create it
                $image = new SimpleImage();
                $image->load("../banners/{$ssOriginal}");
                $image->resizeToWidth(300);
                $image->save("../banners/{$ssThumb}");
                //makeFanartThumb("../banners/$ssOriginal", "../banners/$ssThumb");
            }
            ## Get Fanart Image Dimensions
            list($image_width, $image_height, $image_type, $image_attr) = getimagesize("../banners/{$ssOriginal}");
            $ssWidth = $image_width;
            $ssHeight = $image_height;
            ## Output Fanart XML Branch
            print "<screenshot>\n";
            print "<original width=\"{$ssWidth}\" height=\"{$ssHeight}\">{$ssOriginal}</original>\n";
            print "<thumb>{$ssThumb}</thumb>\n";
            print "</screenshot>\n";
        }
    }
}
Ejemplo n.º 6
0
 /**
  * Generates the thumbnail for a given file.
  */
 protected function _generateThumbnail()
 {
     $image = new SimpleImage();
     $image->load($this->source);
     $image->resizeToWidth(Configure::read('Image.width'));
     $image->save($this->thumb_path);
 }
Ejemplo n.º 7
0
function insertImageSub($file, $sub_id, $menu_id)
{
    $error = false;
    $arr = explode('.', $file["name"]);
    $imageFileType = end($arr);
    if ($file["size"] > 5000000) {
        $error = true;
    }
    if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
        $error = true;
    }
    if (!$error) {
        $target_dir = "../images/menu_" . $menu_id . "/sub_" . $sub_id . "/";
        $target_file = $target_dir . $file["name"];
        //
        if (!file_exists($target_dir)) {
            mkdir($target_dir, 0777, true);
        }
        if (file_exists($target_file)) {
            unlink($target_file);
        }
        if (move_uploaded_file($file["tmp_name"], $target_file)) {
            include 'classSimpleImage.php';
            $image = new SimpleImage();
            $image->load($target_file);
            $image->resize(218, 138);
            $image->save($target_file);
            $arr = explode("../", $target_file);
            return end($arr);
        }
    } else {
        return false;
    }
}
Ejemplo n.º 8
0
 public function action_index()
 {
     $tags = array();
     $imager = new SimpleImage();
     if ($this->request->param('path')) {
         // Берем новость
         $post = ORM::factory('blog')->where('url', '=', $this->request->param('path'))->find();
     } else {
         $post = ORM::factory('blog');
     }
     if ($_POST) {
         $post_name = Arr::get($_POST, 'post_name');
         $post_url = Arr::get($_POST, 'post_url');
         $short_text = Arr::get($_POST, 'short_text');
         $full_text = Arr::get($_POST, 'full_text');
         $tag = Arr::get($_POST, 'tag');
         // Загрузка изображения
         $image = $_FILES["imgupload"]["name"];
         if (!empty($image)) {
             $imager = new SimpleImage();
             //$this->news->deleteImage($post->id);
             //$image = $this->image->upload_image($image['tmp_name'], $image['name'], $this->config->news_images_dir."big/");
             move_uploaded_file($_FILES["imgupload"]["tmp_name"], "files/blog/" . $_FILES["imgupload"]["name"]);
             $imager->load("files/blog/" . $image);
             $imager->resize(200, 200);
             $imager->save("files/blog/miniatures/" . $image);
         }
         $post->set('name', $post_name)->set('url', $post_url)->set('date', DB::expr('now()'))->set('short_text', $short_text)->set('full_text', $full_text)->set('image', $image)->set('tag_id', ORM::factory('tags')->where('name', '=', $tag)->find())->save();
     }
     $tags = ORM::factory('tags')->find_all();
     $content = View::factory('/admin/post')->bind('tags', $tags)->bind('post', $post);
     $this->template->content = $content;
 }
function ImageResize($file)
{
    $image = new SimpleImage();
    $image->load('traffic-images/temp/' . $file);
    $image->resize(300, 200);
    $image->save('traffic-images/' . $file);
    unlink("traffic-images/temp/" . $file);
}
Ejemplo n.º 10
0
 public function Load($pathToImage)
 {
     if (!extension_loaded('gd')) {
         die('gd extension is required for image upload');
     }
     $image = new SimpleImage();
     $image->load($pathToImage);
     return new Image($image);
 }
Ejemplo n.º 11
0
 public function saveImageInFile($file)
 {
     $t = $file['tmp_name'];
     $n = $file['name'];
     $path = App::get("uploads_dir_original") . DIRECTORY_SEPARATOR . $n;
     move_uploaded_file($t, $path);
     $image = new SimpleImage();
     $image->load($path);
     $image->resize(250, 250);
     $image->save(App::get("uploads_dir_small") . DIRECTORY_SEPARATOR . $n);
     return $n;
 }
Ejemplo n.º 12
0
 function upload()
 {
     if (!isset($_FILES['upload'])) {
         $this->directrender('S3/S3');
         return;
     }
     global $params;
     // Params to vars
     $client_id = '1b5cc674ae2f335';
     // Validations
     $this->startValidations();
     $this->validate($_FILES['upload']['error'] === 0, $err, 'upload error');
     $this->validate($_FILES['upload']['size'] <= 10 * 1024 * 1024, $err, 'size too large');
     // Code
     if ($this->isValid()) {
         $fname = $_FILES['upload']['tmp_name'];
         require_once $GLOBALS['dirpre'] . 'includes/S3/SimpleImage.php';
         $image = new SimpleImage();
         $this->validate($image->load($fname), $err, 'invalid image type');
         if ($this->isValid()) {
             if ($image->getHeight() > 1000) {
                 $image->resizeToHeight(1000);
             }
             $image->save($fname);
             function getMIME($fname)
             {
                 $finfo = finfo_open(FILEINFO_MIME_TYPE);
                 $mime = finfo_file($finfo, $fname);
                 finfo_close($finfo);
                 return $mime;
             }
             $filetype = explode('/', getMIME($fname));
             $valid_formats = array("jpg", "png", "gif", "jpeg");
             $this->validate($filetype[0] === 'image' and in_array($filetype[1], $valid_formats), $err, 'invalid image type');
             if ($this->isValid()) {
                 require_once $GLOBALS['dirpre'] . 'includes/S3/s3_config.php';
                 //Rename image name.
                 $actual_image_name = time() . "." . $filetype[1];
                 $this->validate($s3->putObjectFile($fname, $bucket, $actual_image_name, S3::ACL_PUBLIC_READ), $err, 'upload failed');
                 if ($this->isValid()) {
                     $reply = "https://{$bucket}.s3.amazonaws.com/{$actual_image_name}";
                     $this->success('image successfully uploaded');
                     $this->directrender('S3/S3', array('reply' => "up(\"{$reply}\");"));
                     return;
                 }
             }
         }
     }
     $this->error($err);
     $this->directrender('S3/S3');
 }
Ejemplo n.º 13
0
    function uploadArquivo($campoFormulario, $idGravado) {
        $ext = pathinfo($_FILES[$campoFormulario][name], PATHINFO_EXTENSION);

        if (($_FILES[$campoFormulario][name] <> "") && ($_FILES[$campoFormulario][size]) > 0 && in_array(strtolower($ext), $this->extensions)) {
            $arquivoTmp = $_FILES[$campoFormulario]['tmp_name'];
            $nome = str_replace(".", "", microtime(true)) . "_" . $_FILES[$campoFormulario]['name'];

            if (function_exists("exif_imagetype")) {
                $test = exif_imagetype($arquivoTmp);
                $image_type = $test;
            } else {
                $test = getimagesize($arquivoTmp);
                $image_type = $test[2];
            }


            if (in_array($image_type, array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP))) {
                $image = new SimpleImage();
                $image->load($arquivoTmp);
                $l = $image->getWidth();
                $h = $image->getHeight();
                if ($l > $h) {
                    $funcao = "resizeToWidth";
                    $novoTamanho = 1024;
                } else {
                    $funcao = "resizeToHeight";
                    $novoTamanho = 768;
                }

                $image->$funcao($novoTamanho);
                $copiou = $image->save($this->diretorio . $nome);

                if ($this->prefixoMarcaDagua) {
                    $image->$funcao(300);
                    $image->watermark();
                    $image->save($this->diretorio . $this->prefixoMarcaDagua . $nome);
                }
                if ($this->prefixoMiniatura) {
                    $image->load($arquivoTmp);
                    $image->$funcao(380);
                    $image->save($this->diretorio . $this->prefixoMiniatura . $nome);
                }
            } else {
                $copiou = copy($arquivoTmp, $this->diretorio . $nome);
            }
            if ($copiou) {
                $sql = "update $this->tabela set $this->campoBD = '$nome' where id='$idGravado'";
                #$altualizaNome = mysql_query($sql) or die($sql . mysql_error);
                $this->conexao->executeQuery($sql);
            }
        } else {
            return false;
        }
        return $idGravado;
    }
Ejemplo n.º 14
0
function xulyImage($img, $urlImgTemp, $urlImg, $urlImgThumb, $original = 1)
{
    $file = $urlImgTemp . $img;
    $sizeInfo = getimagesize($file);
    if (is_array($sizeInfo)) {
        include_once 'libraries/SimpleImage.php';
        $image = new SimpleImage();
        $image->load($file);
        $width = $sizeInfo[0];
        $height = $sizeInfo[1];
        if ($width <= IMAGE_THUMB_WIDTH && $height <= IMAGE_THUMB_HEIGHT) {
            copy($file, $urlImgThumb . $img);
        } elseif ($width >= $height) {
            $image->resizeToWidth(IMAGE_THUMB_WIDTH);
            $image->save($urlImgThumb . $img);
        } elseif ($width < $height) {
            $image->resizeToHeight(IMAGE_THUMB_HEIGHT);
            $image->save($urlImgThumb . $img);
        }
        if ($original == 1) {
            $image->load($file);
            if ($width >= $height && $width > IMAGE_MAX_WIDTH) {
                $image->resizeToWidth(IMAGE_MAX_WIDTH);
                $image->save($urlImg . $img);
            } elseif ($width <= $height && $height > IMAGE_MAX_HEIGHT) {
                $image->resizeToHeight(IMAGE_MAX_HEIGHT);
                $image->save($urlImg . $img);
            } else {
                copy($file, $urlImg . $img);
            }
            if (file_exists($file)) {
                unlink($file);
            }
        } else {
            if (copy($file, $urlImg . $img)) {
                if (file_exists($file)) {
                    unlink($file);
                }
            }
        }
        return true;
    } else {
        return false;
    }
}
Ejemplo n.º 15
0
function resizeImagesInFolder($dir, $i)
{
    if (!is_dir('cover/' . $dir)) {
        toFolder('cover/' . $dir);
    }
    $files = scandir($dir);
    foreach ($files as $key => $file) {
        if ($file != '.' && $file != '..') {
            if (!is_dir($dir . '/' . $file)) {
                echo $dir . '/' . $file;
                $image = new SimpleImage();
                $image->load($dir . '/' . $file);
                if ($image->getHeight() < $image->getWidth()) {
                    $image->resizeToWidth(1920);
                } else {
                    $image->resizeToHeight(1920);
                }
                // $new = 'cover/' . $dir . '/'.$image->name;
                if ($i < 10) {
                    $new = 'cover/' . $dir . '/00' . $i . '.' . $image->type;
                } elseif ($i < 100) {
                    $new = 'cover/' . $dir . '/0' . $i . '.' . $image->type;
                } else {
                    $new = 'cover/' . $dir . '/' . $i . '.' . $image->type;
                }
                $image->save($new);
                echo ' ---------> ' . $new . '<br>';
                $i++;
            } else {
                resizeImagesInFolder($dir . '/' . $file, 1);
            }
        }
    }
}
Ejemplo n.º 16
0
/**
 * Процесс строит скрипты для вставки ячеек в БД
 * 
 * @param array $argv
 */
function executeProcess(array $argv)
{
    $DM = DirManager::inst(array(__DIR__, 'output'));
    $customNum = $argv[1];
    dolog('Processing mosaic demo, custom num={}', $customNum);
    /* @var $dir DirItem */
    foreach ($DM->getDirContent(null, DirItemFilter::DIRS) as $dir) {
        if (is_inumeric($customNum) && $customNum != $dir->getName()) {
            continue;
            //----
        }
        $imgDM = DirManager::inst($dir->getAbsPath());
        $imgDI = end($imgDM->getDirContent(null, DirItemFilter::IMAGES));
        $map = $imgDM->getDirItem(null, 'map', 'txt')->getFileAsProps();
        $demoDM = DirManager::inst($imgDM->absDirPath(), 'demo');
        $demoDM->clearDir();
        dolog("Building map for: [{}].", $imgDI->getRelPath());
        //CELLS BINDING
        $dim = $imgDM->getDirItem(null, 'settings', 'txt')->getFileAsProps();
        $dim = $dim['dim'];
        $dim = explode('x', $dim);
        $cw = 1 * $dim[0];
        $ch = 1 * $dim[1];
        $sourceImg = SimpleImage::inst()->load($imgDI);
        $w = $sourceImg->getWidth();
        $h = $sourceImg->getHeight();
        $destImg = SimpleImage::inst()->create($w, $h, MosaicImage::BG_COLOR);
        dolog("Img size: [{$w} x {$h}].");
        check_condition($w > 0 && !($w % $cw), 'Bad width');
        check_condition($h > 0 && !($h % $ch), 'Bad height');
        $totalCells = count($map);
        $lengtn = strlen("{$totalCells}");
        //dolog("Cells cnt: [$xcells x $ycells], total: $totalCells.");
        //СТРОИМ КАРТИНКИ
        $secundomer = Secundomer::startedInst();
        //$encoder = new PsGifEncoder();
        for ($cellCnt = 0; $cellCnt <= $totalCells; $cellCnt++) {
            $name = pad_zero_left($cellCnt, $lengtn);
            $copyTo = $demoDM->absFilePath(null, $name, 'jpg');
            if ($cellCnt > 0) {
                $cellParams = $map[$cellCnt];
                $cellParams = explode('x', $cellParams);
                $xCell = $cellParams[0];
                $yCell = $cellParams[1];
                $x = ($xCell - 1) * $cw;
                $y = ($yCell - 1) * $ch;
                $destImg->copyFromAnother($sourceImg, $x, $y, $x, $y, $cw, $ch);
            }
            $destImg->save($copyTo);
            dolog("[{$totalCells}] {$copyTo}");
        }
        //$encoder->saveToFile($demoDM->absFilePath(null, 'animation'));
        $secundomer->stop();
        dolog('Execution time: ' . $secundomer->getTotalTime());
    }
}
Ejemplo n.º 17
0
 function scale($size = 100)
 {
     if (!$this->image && !$this->checked) {
         $this->get();
     }
     if (!$this->image) {
         return false;
     }
     // New code to get rectangular images
     require_once mnminclude . "simpleimage.php";
     $thumb = new SimpleImage();
     $thumb->image = $this->image;
     if ($thumb->resize($size, $size, true)) {
         //$this->image = $thumb->image;
         //$this->x=imagesx($this->image);
         //$this->y=imagesy($this->image);
         return $thumb;
     }
     return false;
 }
Ejemplo n.º 18
0
 public function get_file($modelID = '', $id = '', $filetype = '', $filename = '')
 {
     if ($id != '') {
         $fileinfo = $this->file_model->get_fileinfo($modelID, $id, $filetype);
         if ($fileinfo['Status']) {
             if (file_exists(absolute_path() . APPPATH . 'files/' . $fileinfo['LocalFileName'])) {
                 switch (strtolower($filetype)) {
                     case "thumbnails":
                         $size = explode('_', $filename);
                         if (!is_numeric($size[0]) or $size[0] <= 0) {
                             show_404();
                         }
                         if (!is_numeric($size[1]) or $size[0] <= 0) {
                             show_404();
                         }
                         $img = new SimpleImage();
                         $img->load(absolute_path() . APPPATH . 'files/' . $fileinfo['LocalFileName'])->best_fit($size[0], $size[1]);
                         $img->output('jpg');
                         break;
                     default:
                         $mm_type = mime_content_type($fileinfo['FileName']);
                         header('Content-Description: File Transfer');
                         header('Content-Type: ' . $mm_type);
                         header('Content-Disposition: ' . $fileinfo['DispositionType'] . '; filename=' . basename($fileinfo['FileName']));
                         header('Content-Transfer-Encoding: binary');
                         header('Expires: 0');
                         header('Cache-Control: must-revalidate');
                         header('Pragma: public');
                         header('Content-Length: ' . filesize(APPPATH . 'files/' . $fileinfo['LocalFileName']));
                         ob_clean();
                         flush();
                         readfile(APPPATH . 'files/' . $fileinfo['LocalFileName']);
                 }
             }
         } else {
             show_404();
         }
     } else {
         show_404();
     }
 }
Ejemplo n.º 19
0
 /**
  * Создание новости
  */
 public function create()
 {
     if (!User::isAdmin()) {
         App::abort('403');
     }
     if (Request::isMethod('post')) {
         $news = new News();
         $news->category_id = Request::input('category_id');
         $news->user_id = User::get('id');
         $news->title = Request::input('title');
         $news->slug = '';
         $news->text = Request::input('text');
         $image = Request::file('image');
         if ($image && $image->isValid()) {
             $ext = $image->getClientOriginalExtension();
             $filename = uniqid(mt_rand()) . '.' . $ext;
             if (in_array($ext, ['jpeg', 'jpg', 'png', 'gif'])) {
                 $img = new SimpleImage($image->getPathName());
                 $img->best_fit(1280, 1280)->save('uploads/news/images/' . $filename);
                 $img->best_fit(200, 200)->save('uploads/news/thumbs/' . $filename);
             }
             $news->image = $filename;
         }
         if ($news->save()) {
             if ($tags = Request::input('tags')) {
                 $tags = array_map('trim', explode(',', $tags));
                 foreach ($tags as $tag) {
                     $tag = Tag::create(['name' => $tag]);
                     $tag->create_news_tags(['news_id' => $news->id]);
                 }
             }
             App::setFlash('success', 'Новость успешно создана!');
             App::redirect('/' . $news->category->slug . '/' . $news->slug);
         } else {
             App::setFlash('danger', $news->getErrors());
             App::setInput($_POST);
         }
     }
     $categories = Category::getAll();
     App::view('news.create', compact('categories'));
 }
 private function _write_product_image($file = '', $prd_id = '')
 {
     $val = rand(999, 99999999);
     $image_name = "PRO" . $val . $prd_id . ".png";
     //$this->upload_image($file, $image_name);
     $this->request->data['Product']['image'] = $image_name;
     $this->request->data['Product']['id'] = $prd_id;
     $this->Product->save($this->request->data, false);
     /* if (!empty($file)) {
            $this->FileWrite->file_write_path = PRODUCT_IMAGE_PATH;
            $this->FileWrite->_write_file($file, $image_name);
        }*/
     include "SimpleImage.php";
     $image = new SimpleImage();
     if (!empty($file)) {
         $image->load($file['tmp_name']);
         $image->save(PRODUCT_IMAGE_PATH . $image_name);
         $image->resizeToWidth(150, 150);
         $image->save(PRODUCT_IMAGE_THUMB_PATH . $image_name);
     }
 }
Ejemplo n.º 21
0
 public static function get($image_url, $width = NULL)
 {
     $cached_image = '';
     if (!empty($image_url)) {
         // Get file name
         $exploded_image_url = explode("/", $image_url);
         $image_filename = end($exploded_image_url);
         $exploded_image_filename = explode(".", $image_filename);
         $extension = end($exploded_image_filename);
         // Image validation
         if (strtolower($extension) == "gif" || strtolower($extension) == "jpg" || strtolower($extension) == "png") {
             $cached_image = self::$image_path . $image_filename;
             // Check if image exists
             if (file_exists($cached_image)) {
                 return $cached_image;
             } else {
                 // Get remote image
                 $ch = curl_init();
                 curl_setopt($ch, CURLOPT_URL, $image_url);
                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                 $image_to_fetch = curl_exec($ch);
                 curl_close($ch);
                 // Save image
                 $local_image_file = fopen($cached_image, 'w+');
                 chmod($cached_image, 0755);
                 fwrite($local_image_file, $image_to_fetch);
                 fclose($local_image_file);
                 // Resize image
                 if (!is_null($width)) {
                     $image = new SimpleImage();
                     $image->load($cached_image);
                     $image->resizeToWidth($width);
                     $image->save($cached_image);
                 }
             }
         }
     }
     return $cached_image;
 }
Ejemplo n.º 22
0
 function InsertMemory($memorydate, $imgname, $userid, $location, $title)
 {
     global $objSmarty, $config;
     if ($this->con->Conectar() == true) {
         $memdate = $this->changeDateformut($memorydate);
         $memoryphoto = "";
         $root_url = $_SERVER[DOCUMENT_ROOT] . '/memoryphoto/';
         $location_url = $_SERVER[DOCUMENT_ROOT] . '/includes/app/pics_temp/';
         if ($imgname != "") {
             $resizeObj = new SimpleImage($location . $imgname);
             if ($width >= "1000") {
                 $resizeObj->resize(800, 650);
                 $resizeObj->save($root_url . $imgname);
             }
             if ($width >= "800" && $width < "1000") {
                 $resizeObj->resize(600, 460);
                 $resizeObj->save($root_url . $imgname);
             }
             if ($width >= "600" && $width < "800") {
                 $resizeObj->resize(400, 260);
                 $resizeObj->save($root_url . $imgname);
             }
             $name = $imgname;
             //@move_uploaded_file($_FILES['memoryphoto']['tmp_name'], "memoryphoto/".$name);exit;
             $memoryphoto = " `MemoryPhoto` = '" . addslashes($imgname) . "', ";
             $resizeObj = new SimpleImage($location . $name);
             $resizeObj->resize(160, 160);
             $resizeObj->save($root_url . "thumbnail/" . $name);
             $memoryphotothumb = " `MemoryPhotoThumbnail` = '" . addslashes($name) . "', ";
             $resizeObj->resize(850, 450);
             $resizeObj->save($root_url . "850x450/" . $name);
             $resizeObj->resize(300, 290);
             $resizeObj->save($root_url . "300x290/" . $name);
             $filename = $root_url . $name;
             rename($location . $name, $filename);
         } else {
             //echo "ELSE";exit;
             $memoryphoto = " `MemoryPhoto` = 'photo_not_available.jpg', ";
             //$memoryphoto=" `MemoryPhoto` = ".'photo_not_available.jpg'.',';
             $memoryphotothumb = " `MemoryPhotoThumbnail` = 'photo_not_available.jpg', ";
         }
         $InsQuery = "INSERT INTO `tbl_mymemories` \n\t\t\tset `MemberID`= '" . $userid . "' ,\n\t\t\t`MemoryTitle`= '" . addslashes($title) . "',\n\t\t\t`MemoryDate`= '" . $memdate . "' ,\n\t\t\t{$memoryphoto} \n\t\t\t{$memoryphotothumb} \n\t\t\t`Status`= '1' ,\n\t\t\t`CreatedDateTime`= NOW()";
         $insertid = mysql_query($InsQuery);
         $last_insert_id = mysql_insert_id();
         /* Insert For Showing The Recent Activities Starts Here */
         $activity_comment = "created new memory from app.";
         $Recent_Activity = "INSERT INTO `tbl_recent_activity` \n\t\t\t(`activity_id`, `A_MemberID`,`A_FriendID`, `Added_Page`, `Activity_Comment`, `Table_Fetch`, `PhotoId`, `Privacy`, `Status`, `createdtime`) \n\t\t\tVALUES ('','" . $userid . "','','Memory','" . $activity_comment . "','memory','" . $last_insert_id . "','1','1',now())";
         $Recent_Insert = mysql_query($Recent_Activity);
         return "MEmory has been created successfully.";
     } else {
         return "Database Error";
     }
 }
Ejemplo n.º 23
0
 public function bindImage($elementName)
 {
     $file = JRequest::getVar($elementName, '', 'FILES');
     if (!isset($file['tmp_name']) || empty($file['tmp_name'])) {
         return false;
     }
     jimport('joomla.filesystem.file');
     jimport('joomla.filesystem.folder');
     // @task: Test if the folder containing the badges exists
     if (!JFolder::exists(DISCUSS_BADGES_PATH)) {
         JFolder::create(DISCUSS_BADGES_PATH);
     }
     // @task: Test if the folder containing uploaded badges exists
     if (!JFolder::exists(DISCUSS_BADGES_UPLOADED)) {
         JFolder::create(DISCUSS_BADGES_UPLOADED);
     }
     require_once DISCUSS_CLASSES . '/simpleimage.php';
     $image = new SimpleImage();
     $image->load($file['tmp_name']);
     if ($image->getWidth() > 64 || $image->getHeight() > 64) {
         return false;
     }
     $storage = DISCUSS_BADGES_UPLOADED;
     $name = md5($this->id . DiscussHelper::getDate()->toMySQL()) . $image->getExtension();
     // @task: Create the necessary path
     $path = $storage . '/' . $this->id;
     if (!JFolder::exists($path)) {
         JFolder::create($path);
     }
     // @task: Copy the original image into the storage path
     JFile::copy($file['tmp_name'], $path . '/' . $name);
     // @task: Resize to the 16x16 favicon
     $image->resize(DISCUSS_BADGES_FAVICON_WIDTH, DISCUSS_BADGES_FAVICON_HEIGHT);
     $image->save($path . '/' . 'favicon_' . $name);
     $this->avatar = $this->id . '/' . $name;
     $this->thumbnail = $this->id . '/' . 'favicon_' . $name;
     return $this->store();
 }
Ejemplo n.º 24
0
 public function createSmallCovers($forceRecr = false)
 {
     /* @var $ex GymEx */
     foreach ($this->getExercises() as $ex) {
         $curImg = $this->absCoverPath($ex->getId());
         if (!PsImg::isImg($curImg)) {
             continue;
         }
         $imgNew = $this->absCoverPathSmall($ex->getId());
         if (!PsImg::isImg($imgNew) || $forceRecr) {
             SimpleImage::inst()->load($curImg)->resizeSmart($this->dim, $this->dim)->save($imgNew)->close();
         }
     }
 }
Ejemplo n.º 25
0
function imageResize($filename, $cleanFilename, $target)
{
    if (!file_exists($cleanFilename)) {
        $dims = getimagesize($filename);
        $width = $dims[0];
        $height = $dims[1];
        //takes the larger size of the width and height and applies the formula accordingly...this is so this script will work dynamically with any size image
        if ($width > $height) {
            $percentage = $target / $width;
        } else {
            $percentage = $target / $height;
        }
        //gets the new value and applies the percentage, then rounds the value
        $width = round($width * $percentage);
        $height = round($height * $percentage);
        $image = new SimpleImage();
        $image->load($filename);
        $image->resize($width, $height);
        $image->save($cleanFilename);
        $image = null;
    }
    //returns the new sizes in html image tag format...this is so you can plug this function inside an image tag and just get the
    return "src=\"{$baseurl}/{$cleanFilename}\"";
}
Ejemplo n.º 26
0
/**
 * Конвертирует картинки в .png
 * 
 * @param array $argv
 */
function executeProcess(array $argv)
{
    $SRC_DIR = 'source';
    $OUT_DIR = 'output';
    $dm = DirManager::inst(__DIR__);
    //Создадим $SRC_DIR
    $dm->makePath($SRC_DIR);
    //Перенесём все картинки из корня в $SRC_DIR
    $items = $dm->getDirContent(null, DirItemFilter::IMAGES);
    /* @var $img DirItem */
    foreach ($items as $img) {
        $img->copyTo($dm->absFilePath($SRC_DIR, $img->getName()))->remove();
    }
    //Очистим $OUT_DIR
    $dm->clearDir($OUT_DIR)->makePath($OUT_DIR);
    //Список картинок
    $items = $dm->getDirContent($SRC_DIR, DirItemFilter::IMAGES);
    /* @var $img DirItem */
    foreach ($items as $img) {
        SimpleImage::inst()->load($img)->resizeSmart(36, 36)->save($dm->absFilePath($OUT_DIR, $img->getNameNoExt(), 'png'), IMAGETYPE_PNG)->close();
    }
}
Ejemplo n.º 27
0
 /**
  * Анимация
  */
 public function getAnimation()
 {
     if (isset($this->animation)) {
         return $this->animation;
     }
     check_condition($this->IMAGES, 'No images for gif');
     PsLibs::inst()->GifEncoder();
     $frames = array();
     $framed = array();
     foreach ($this->IMAGES as $path => $delay) {
         ob_start();
         SimpleImage::inst()->load($path)->output(IMAGETYPE_GIF)->close();
         $frames[] = ob_get_contents();
         $framed[] = $delay;
         // Delay in the animation.
         ob_end_clean();
     }
     // Generate the animated gif and output to screen.
     $gif = new GIFEncoder($frames, $framed, 0, 2, 0, 0, 0, 'bin');
     $this->animation = $gif->GetAnimation();
     return $this->animation;
 }
Ejemplo n.º 28
0
 static function Thumbnail($image_file, $thumb_file, $width = 48, $height = 48)
 {
     $ctype = FSS_Helper::datei_mime("png");
     // thumb file exists
     if (file_exists($thumb_file) && filesize($thumb_file) > 0) {
         header("Content-Type: " . $ctype);
         header('Cache-control: max-age=' . 60 * 60 * 24 * 365);
         header('Expires: ' . gmdate(DATE_RFC1123, time() + 60 * 60 * 24 * 365));
         @readfile($thumb_file);
         exit;
     }
     require_once JPATH_SITE . DS . 'components' . DS . 'com_fss' . DS . 'helper' . DS . 'third' . DS . 'simpleimage.php';
     $im = new SimpleImage();
     $im->load($image_file);
     if (!$im->image) {
         // return a blank thumbnail of some sort!
         $im->load(JPATH_SITE . DS . 'components' . DS . 'com_fss' . DS . 'assets' . DS . 'images' . DS . 'blank_16.png');
     }
     $im->resize($width, $height);
     $im->output();
     $im_data = ob_get_clean();
     if (strlen($im_data) > 0) {
         // if so use JFile to write the thumbnail image
         JFile::write($thumb_file, $im_data);
     } else {
         // it failed for some reason, try doing a direct write of the thumbnail
         $im->save($thumb_file);
     }
     header('Cache-control: max-age=' . 60 * 60 * 24 * 365);
     header('Expires: ' . gmdate(DATE_RFC1123, time() + 60 * 60 * 24 * 365));
     header("Content-Type: " . $ctype);
     if (file_exists($thumb_file && filesize($thumb_file) > 0)) {
         @readfile($thumb_file);
     } else {
         $im->output();
     }
     exit;
 }
Ejemplo n.º 29
0
 public function bindAttachments()
 {
     $mainframe = JFactory::getApplication();
     $config = DiscussHelper::getConfig();
     // @task: Do not allow file attachments if its disabled.
     if (!$config->get('attachment_questions')) {
         return false;
     }
     $allowed = explode(',', $config->get('main_attachment_extension'));
     $files = JRequest::getVar('filedata', array(), 'FILES');
     if (empty($files)) {
         return false;
     }
     $total = count($files['name']);
     // @rule: Handle empty files.
     if (empty($files['name'][0])) {
         $total = 0;
     }
     if ($total < 1) {
         return false;
     }
     jimport('joomla.filesystem.file');
     jimport('joomla.filesystem.folder');
     jimport('joomla.utilities.utility');
     // @rule: Create default media path
     $path = DISCUSS_MEDIA . '/' . trim($config->get('attachment_path'), DIRECTORY_SEPARATOR);
     if (!JFolder::exists($path)) {
         JFolder::create($path);
         JFile::copy(DISCUSS_ROOT . '/index.html', $path . '/index.html');
     }
     $maxSize = (double) $config->get('attachment_maxsize') * 1024 * 1024;
     for ($i = 0; $i < $total; $i++) {
         $extension = JFile::getExt($files['name'][$i]);
         // Skip empty data's.
         if (!$extension) {
             continue;
         }
         // @rule: Check for allowed extensions
         if (!isset($extension) || !in_array(strtolower($extension), $allowed)) {
             $mainframe->enqueueMessage(JText::sprintf('COM_EASYDISCUSS_FILE_ATTACHMENTS_INVALID_EXTENSION', $files['name'][$i]), 'error');
             $this->setError(JText::sprintf('COM_EASYDISCUSS_FILE_ATTACHMENTS_INVALID_EXTENSION', $files['name'][$i]));
             return false;
         } else {
             $size = $files['size'][$i];
             // @rule: File size should not exceed maximum allowed size
             if (!empty($size) && ($size < $maxSize || $maxSize == 0)) {
                 $name = DiscussHelper::getHash($files['name'][$i] . DiscussHelper::getDate()->toMySQL());
                 $attachment = DiscussHelper::getTable('Attachments');
                 $attachment->set('path', $name);
                 $attachment->set('title', $files['name'][$i]);
                 $attachment->set('uid', $this->id);
                 $attachment->set('type', $this->getType());
                 $attachment->set('created', DiscussHelper::getDate()->toMySQL());
                 $attachment->set('published', true);
                 $attachment->set('mime', $files['type'][$i]);
                 $attachment->set('size', $size);
                 JFile::copy($files['tmp_name'][$i], $path . '/' . $name);
                 $attachment->store();
                 // Create a thumbnail if attachment is an image
                 if (DiscussHelper::getHelper('Image')->isImage($files['name'][$i])) {
                     require_once DISCUSS_CLASSES . '/simpleimage.php';
                     $image = new SimpleImage();
                     $image->load($files['tmp_name'][$i]);
                     $image->resizeToFill(160, 120);
                     $image->save($path . '/' . $name . '_thumb', $image->image_type);
                 }
             } else {
                 $mainframe->enqueueMessage(JText::sprintf('COM_EASYDISCUSS_FILE_ATTACHMENTS_MAX_SIZE_EXCLUDED', $files['name'][$i], $config->get('attachment_maxsize')), 'error');
                 $this->setError(JText::sprintf('COM_EASYDISCUSS_FILE_ATTACHMENTS_MAX_SIZE_EXCLUDED', $files['name'][$i], $config->get('attachment_maxsize')));
                 return false;
             }
         }
     }
     return true;
 }
Ejemplo n.º 30
0
 /**
  * Загрузка фото в профиль
  */
 public function image()
 {
     if (!Request::ajax() || !User::check()) {
         App::redirect('/');
     }
     // Удаление и размер
     $image = Request::file('image');
     if ($image->isValid()) {
         $ext = $image->getClientOriginalExtension();
         if (in_array($ext, ['jpeg', 'jpg', 'png', 'gif'])) {
             $filename = uniqid(mt_rand()) . '.' . $ext;
             $user = User::get();
             $user->deleteImages();
             $img = new SimpleImage($image->getPathName());
             $img->best_fit(1280, 1280)->save('uploads/users/photos/' . $filename);
             $img->best_fit(200, 200)->save('uploads/users/thumbs/' . $filename);
             $img->thumbnail(48, 48)->save('uploads/users/avatars/' . $filename);
             $user->avatar = $filename;
             if ($user->save()) {
                 exit(json_encode(['status' => 'uploaded']));
             } else {
                 exit(json_encode(['status' => 'nosave']));
             }
         } else {
             exit(json_encode(['status' => 'invalid']));
         }
     }
 }