function post_resource($data) { if ($this->storage->dir->exists) { return so_output::conflict('Image already exists'); } $this->storage->dir->exists = true; $image = new \Imagick((string) $data['file']); $image->writeImage((string) $this->fileOrinal); $size = $image->getImageGeometry(); if ($size['width'] > 800 or $size['height'] > 600) { $image->adaptiveResizeImage(800, 600, true); } $image->writeImage((string) $this->fileMaximal); $size = $image->getImageGeometry(); if ($size['width'] > 100 or $size['height'] > 100) { $image->adaptiveResizeImage(100, 100, true); } $image->writeImage((string) $this->filePreview); return so_output::ok()->content($this->model); }
/** * (non-PHPdoc) * @see Imagine\ImageInterface::resize() */ public function resize(BoxInterface $size) { try { $this->imagick->adaptiveResizeImage($size->getWidth(), $size->getHeight()); } catch (\ImagickException $e) { throw new RuntimeException('Resize operation failed', $e->getCode(), $e); } return $this; }
function thumb($pdffile, $jpegfile, $width, $output = false) { list($src_width, $src_height, $src_type, $src_attr) = imgetimagesize($pdffile); list($tgt_width, $tgt_height, $tgt_type, $tgt_attr) = setimagesize($pdffile, $width); $ii = pathinfo($pdffile); $input = trim(strtolower(str_replace('.','',$ii['extension']))); $output = (!$output ? $input : $output); if (class_exists('Imagick')) { $im = new Imagick(); $im->setResolution( 300, 300 ); if ($input == "pdf") { $im->readImage($pdffile.'[0]'); $im->cropImage(($src_width - 60),($src_height - 60),30,30); } else { $im->readImage($pdffile); } // $im->setImageColorspace(Imagick::COLORSPACE_SRGB); $im->adaptiveResizeImage($tgt_width, $tgt_height, true); $im->setImageFormat("jpg"); //$im->setImageCompressionQuality(100); $im->writeImage($jpegfile); } else { if ($input == "gif") { $im = imagecreatefromgif($pdffile); $it = imagecreate($tgt_width, $tgt_height); } elseif ($input == "png") { $im = imagecreatefrompng($pdffile); $it = imagecreatetruecolor($tgt_width, $tgt_height); imagealphablending($it, false); imagesavealpha($it,true); $transparent = imagecolorallocatealpha($it, 255, 255, 255, 127); imagefilledrectangle($it, 0, 0, $tgt_width, $tgt_height, $transparent); } else { $im = imagecreatefromjpeg($pdffile); $it = imagecreatetruecolor($tgt_width, $tgt_height); } imagecopyresampled($it, $im, 0, 0, 0, 0, $tgt_width, $tgt_height, $src_width, $src_height); if ($output == "gif") { imagegif($it, $jpegfile); } elseif ($output == "png") { imagepng($it, $jpegfile); } else { imagejpeg($it, $jpegfile); } } }
function getImageHistogram($imagePath) { $backgroundColor = 'black'; $draw = new \ImagickDraw(); $draw->setStrokeWidth(0); //make the lines be as thin as possible $imagick = new \Imagick(); $imagick->newImage(500, 500, $backgroundColor); $imagick->setImageFormat("png"); $imagick->drawImage($draw); $histogramWidth = 256; $histogramHeight = 100; // the height for each RGB segment $imagick = new \Imagick(realpath($imagePath)); //Resize the image to be small, otherwise PHP tends to run out of memory //This might lead to bad results for images that are pathologically 'pixelly' $imagick->adaptiveResizeImage(200, 200, true); $histogramElements = $imagick->getImageHistogram(); $histogram = new \Imagick(); $histogram->newpseudoimage($histogramWidth, $histogramHeight * 3, 'xc:black'); $histogram->setImageFormat('png'); $getMax = function ($carry, $item) { if ($item > $carry) { return $item; } return $carry; }; $colorValues = ['red' => getColorStatistics($histogramElements, \Imagick::COLOR_RED), 'lime' => getColorStatistics($histogramElements, \Imagick::COLOR_GREEN), 'blue' => getColorStatistics($histogramElements, \Imagick::COLOR_BLUE)]; $max = array_reduce($colorValues['red'], $getMax, 0); $max = array_reduce($colorValues['lime'], $getMax, $max); $max = array_reduce($colorValues['blue'], $getMax, $max); $scale = $histogramHeight / $max; $count = 0; foreach ($colorValues as $color => $values) { $draw->setstrokecolor($color); $offset = ($count + 1) * $histogramHeight; foreach ($values as $index => $value) { $draw->line($index, $offset, $index, $offset - $value * $scale); } $count++; } $histogram->drawImage($draw); header("Content-Type: image/png"); echo $histogram; }
public static function resizeImage($curImagePath, $newImagePath, $width, $height) { try { if ($curImagePath == '') { return false; } if ($width == '' || $width == 0) { $width = 90; } if ($height == '' || $height == 0) { $height = 90; } $image = new \Imagick($curImagePath); $image->adaptiveResizeImage($width, $height); $image->setImageFormat("png"); $image->writeImage($newImagePath); return true; } catch (Exception $e) { //echo $e->getMessage(); return false; } }
/** * Scales the image to a specific width and height * * @param string $outputFile The output file * @param int $w The width * @param int $h The height * @return string The path to the scaled file */ public function scaleTo($outputFile, $w, $h) { $image = new \Imagick(); $image->readImage($this->image->getFilename()); $image->adaptiveResizeImage($w, $h); $image->writeImage($outputFile); return $outputFile; }
public function foto($id = NULL) { if ($id === NULL) { $mensajes[] = array('error' => "Parámetros incorrectos para acceder a subida de foto de perfil, por favor, intentelo de nuevo."); $this->flashdata->load($mensajes); redirect('usuarios/login'); } $data['id'] = $id; $data['error'] = array(); if ($this->input->post('insertar') !== NULL) { $config['upload_path'] = 'images/usuarios/'; $config['allowed_types'] = 'jpeg|jpg|jpe'; $config['overwrite'] = TRUE; $config['max_width'] = '250'; $config['max_height'] = '250'; $config['max_size'] = '100'; $config['file_name'] = $id . '.jpeg'; $this->load->library('upload', $config); if (!$this->upload->do_upload('foto')) { $data['error'] = $this->upload->display_errors(); } else { $data = array('upload_data' => $this->upload->data()); $imagen = new Imagick($data['upload_data']['full_path']); $imagen->adaptiveResizeImage(70, 70); $imagen->writeImageFile(fopen("images/usuarios/" . $id . "_thumbnail.jpeg", "w")); redirect('usuarios/perfil/' . $id); } } $this->template->load('usuarios/foto', $data); }
/** * Simples resize broken ratio * * @param \Imagick image * @param integer width * @@param integer height */ public function adaptive(\Imagick $image, $width, $height) { $image->adaptiveResizeImage($width, $height); $image->unsharpMaskImage(0 , 0.5 , 1 , 0.05); }
function admin_files_create() { // Require admin login if(!(isset($_SESSION['active_user']) && $_SESSION['active_user']['type'] == 'admin')) redirect_to('/'); $this->load_outer_template('admin'); $m_files = instance_model('files'); if(isset($_POST['Submit'])) { $file_name = $_FILES['file']['name']; $file_mime = $_FILES['file']['type']; $error = false; if(!in_array(strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION)), $GLOBALS['allowed_ext_files'])) { $error = true; new_flash('File type is not allowed',1); } else { $is_image = false; $unique_id = sha1(time()); $tmppath = TMPFILES . '/' . $unique_id . '_' . $_FILES['file']['name']; if(isset($_FILES['file']) && move_uploaded_file($_FILES['file']['tmp_name'], $tmppath)) { // preprocess images try { $is_image = true; $im = new Imagick($tmppath); $im->adaptiveResizeImage('620','620', true); $im->writeImage($tmppath); $im->destroy(); } // Handle outher file types catch(exception $e){ $is_image = false; } } else { $error = true; new_flash('File failed to upload',1); } } if($error == false) { $newloc = 'res/files/'; // Check name is unique $hard_file_name = $file_name; $ctr = 0; for(;;) { if($ctr > 200) throw new exception('Could not create unique file name'); if(file_exists($newloc . $hard_file_name)) { $ctr += 1; // add number to file name $split_name = explode('.', $file_name); $base = array_shift($split_name); $ext = implode('.', $split_name); $hard_file_name = $base . '_' . $ctr . '.' . $ext; } else break; } $file_name = $hard_file_name; // move image file rename($tmppath, $newloc . $file_name); $size = filesize($newloc . $file_name); if($is_image) { // generate thumbnail $im = new Imagick($newloc . $file_name); $im->cropThumbnailImage('130','98'); $im->writeImage($newloc . 'thumbs/' . $file_name); $im->destroy(); } $m_files->create($file_name, $size, $file_mime, $is_image); redirect_to(make_url('files', 'admin_files')); } } $view = instance_view('files/admin/upload'); $view = $view->parse_to_variable(array( 'form_url' => make_url('files', 'admin_files_create'), 'back_url' => make_url('files', 'admin_files'), 'title' => 'Upload file' )); $this->set_template_paramiters(array( 'content' => $view )); }
public function svgToPng($svg, $outputName = 'svg', $outputDir = 'data/img/', $width = 800, $height = 600) { // exit(); exec("convert -version", $out); //On teste la présence d'imagick sur le serveur if (!empty($out)) { $im = new Imagick(); $imagick->setBackgroundColor(new ImagickPixel('transparent')); $im->readImageBlob($svg); /*png settings*/ $im->setImageFormat("png24"); $im->resizeImage($width, $height, imagick::FILTER_LANCZOS, 1); /*Optional, if you need to resize*/ /*jpeg*/ $im->setImageFormat("jpeg"); $im->adaptiveResizeImage($width, $height); /*Optional, if you need to resize*/ $im->writeImage(SIG_ROOT . $outputDir . $outputName . '.png'); $im->writeImage(SIG_ROOT . $outputDir . $outputName . '.jpg'); $im->clear(); $im->destroy(); echo '<img src="' . Router::url($outputDir . $outputName . '.png') . '" alt="' . $outputName . '.png" />'; } }
/** * @param int $dw * @param bool $pdfLogo * @param int $pdfLogoSize */ public function showImg($dw = 500, $pdfLogo = false, $pdfLogoSize = 128) { $cachename = $this->fullpath . $dw . $this->pageid . ".png"; $cacheimg = $this->cachepath . '/' . $this->_nameFilter($cachename); if (class_exists('Imagick')) { try { $im = $this->_dataCacher($cachename); if ($im === false) { $this->_logToFile('File not in cache'); $im = new imagick($this->fullpath . '[' . $this->pageid . ']'); //$im->setSize($dw*2,$dw*2); $im->setImageFormat("png"); $im->adaptiveResizeImage($dw, $dw, true); // add a border to the image $color = new ImagickPixel(); $color->setColor("rgb(200,200,200)"); $im->borderImage($color, 1, 1); // draw the PDF icon on top of the PDF preview if ($pdfLogo) { $pdflogo = new Imagick($this->assetsPath . $this->deficon); $pdflogo->adaptiveResizeImage($pdfLogoSize, $pdfLogoSize); $im->compositeImage($pdflogo, Imagick::COMPOSITE_DEFAULT, 1, 1); } $this->_dataCacher($cachename, $im); $im->writeImage($cacheimg); } else { $this->_logToFile('File IS cached'); } header("Content-Type: image/png"); header("Content-Disposition: attachment; filename=\"" . $cachename . ".png\";"); $this->getRawFile($cacheimg, false, 'PNG', true); } catch (Exception $e) { return parent::showImg($dw); } } else { return parent::showImg($dw); } }
static function nonImageAddTexte($text, $fontfile, $fontsize) { $svg = '<?xml version="1.0" encoding="utf-8"?> <!-- The icon can be used freely in both personal and commercial projects with no attribution required, but always appreciated. You may NOT sub-license, resell, rent, redistribute or otherwise transfer the icon without express written permission from iconmonstr.com --> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="512px" height="512px" viewBox="0 0 512 512" xml:space="preserve"> <defs> <linearGradient id="degrade" x1="100%" y1="0" x2="100%" y2="100%"> <stop offset="0%" style="stop-color:#898989; stop-opacity:0.2;"/> <stop offset="40%" style="stop-color:#464646; stop-opacity:1;"/> <stop offset="100%" style="stop-color:#111111; stop-opacity:0.7;"/> </linearGradient> <linearGradient id="degrade1" x1="100%" y1="0" x2="100%" y2="100%"> <stop offset="0%" style="stop-color:#111111; stop-opacity:0.7;"/> <stop offset="40%" style="stop-color:#AAAAAA; stop-opacity:1;"/> <stop offset="100%" style="stop-color:#F0F0F0; stop-opacity:0.2;"/> </linearGradient> <style type="text/css"> #stop1{ stop-color:chartreuse; stop-opacity:0.2; } #stop2{ stop-color:cornflowerblue; stop-opacity:1; } #stop3{ stop-color:chartreuse; stop-opacity:0.7; } </style> </defs> <path style="fill:url(#degrade); stroke:#BBBBBB; stroke-width:2px;" id="video-icon" d="M50,60.345v391.311h412V60.345H50z M137.408,410.862H92.354v-38.747h45.055V410.862z M137.408,343.278 H92.354v-38.747h45.055V343.278z M137.408,275.372H92.354v-38.747h45.055V275.372z M137.408,208.111H92.354v-38.748h45.055V208.111z M137.408,140.526H92.354v-38.747h45.055V140.526z M337.646,410.862H177.961V275.694h159.685V410.862z M337.646,236.947H177.961 V101.779h159.685V236.947z M423.253,410.862h-45.054v-38.747h45.054V410.862z M423.253,343.278h-45.054v-38.747h45.054V343.278z M423.253,275.372h-45.054v-38.747h45.054V275.372z M423.253,208.111h-45.054v-38.748h45.054V208.111z M423.253,140.526h-45.054 v-38.747h45.054V140.526z"/> </svg> '; $im2 = new \Imagick(); $im2->setBackgroundColor(new \ImagickPixel('transparent')); $im2->readimageblob($svg); $im2->setImageFormat("png"); $im2->adaptiveResizeImage(140, 140); /*Optional, if you need to resize*/ //return $im2->getimageblob(); $im = new \Imagick(); $im->newimage(260, 300, new \ImagickPixel('#999999'), "jpeg"); $im->compositeimage($im2, \Imagick::COMPOSITE_DEFAULT, 60, 80); $widthmax = $im->getImageGeometry()["width"]; $draw = new \ImagickDraw(); /* On commence un nouveau masque nommé "gradient" */ $draw->setFillColor('#FFFFFF'); /* Font properties */ $draw->setFont($fontfile); $draw->setFontSize($fontsize); $draw->setGravity(\Imagick::GRAVITY_NORTH); $words = explode(' ', $text); //Test si la fontsize n'est pas trop grosse pour un mot $i = 0; while ($i < count($words)) { $lineSize = $im->queryfontmetrics($draw, $words[$i])["textWidth"]; if ($lineSize < $widthmax) { $i++; } else { $fontsize--; $draw->setFontSize($fontsize); } } $res = $words[0]; for ($i = 1; $i < count($words); $i++) { $lineSize = $im->queryfontmetrics($draw, $res . " " . $words[$i]); if ($lineSize["textWidth"] < $widthmax) { $res .= " " . $words[$i]; } else { $res .= "\n" . $words[$i]; } } /* Create text */ $im->annotateImage($draw, 0, 0, 0, $res); return $im->getimageblob(); }
function createFavicon() { $favicon_image = $this->_params->get('favicon_image'); $favicon_path = 'templates/blank_j3/favicon/'; if (isset($favicon_image)) { if (!is_dir(__DIR__ . '/../favicon')) { mkdir(__DIR__ . '/../favicon', 0777, true); } $favicon_set = array('apple-touch-icon' => array(57, 60, 72, 76, 114, 120, 144, 152), 'favicon' => array(16, 32, 96, 160, 196), 'mstile' => array(70, 144, 150, 310)); $return_favicons = ''; // create favicons for all except Win foreach ($favicon_set as $name => $sizes) { foreach ($sizes as $size) { $favicon_name = "{$name}-{$size}" . "x{$size}.png"; $outFile = __DIR__ . "/../favicon/{$favicon_name}"; $image = new Imagick($favicon_image); $image->adaptiveResizeImage($size, $size, true); $image->setImageBackgroundColor('None'); $image->thumbnailImage($size, $size, 1, 'None'); $image->writeImage($outFile); //echo "<img src='$favicon_path/$favicon_name' />"; if ($name != 'mstile') { $return_favicons .= "<link rel='{$name}' sizes='{$size}" . "x{$size}' href='{$favicon_path}/{$favicon_name}'>"; } unset($image); } } // create favicon for Win // generate XML $tile_bg_win = $this->_params->get('bg_win'); $xml_data = <<<XML <?xml version="1.0" encoding="utf-8"?> <browserconfig> <msapplication> <tile> <square70x70logo src="{$favicon_path}/mstile-70x70.png"/> <square150x150logo src="{$favicon_path}/mstile-150x150.png"/> <square310x310logo src="{$favicon_path}/mstile-310x310.png"/> <wide310x150logo src="{$favicon_path}/mstile-310x150.png"/> <TileColor>{$tile_bg_win}</TileColor> </tile> </msapplication> </browserconfig> XML; file_put_contents(__DIR__ . "/../favicon/browserconfig.xml", $xml_data); $return_favicons .= "<meta name='msapplication-TileColor' content='{$tile_bg_win}'>"; $return_favicons .= "<meta name='msapplication-TileImage' content='{$favicon_path}/mstile-144x144.png'>"; $return_favicons .= "<meta name='msapplication-config' content='{$favicon_path}/browserconfig.xml'>"; // generate favicon.ico $image = new Imagick($favicon_image); $image->cropThumbnailImage(32, 32); $image->setFormat('ico'); $image->writeImage("{$favicon_path}/favicon.ico"); unset($image); $return_favicons .= "<link rel='shortcut icon' href='{$favicon_path}/favicon.ico'>"; return $return_favicons; } }
public function processEpub() { $this->getContent($this->getTitle()); $this->cleanContent($this->content); $this->getImagesURL($this->content); $this->removeBeforeHeader($this->content); $this->trimHeaders($this->content); $this->replaceIMG($this->content, $this->noImages); $this->getTOC($this->content); $this->constructNCX($this->ncx_navmap, $this->getUuid(), $this->depth, $this->fileName); $this->constructOPF(); $this->constructCover(); $this->constructContent(); if (!empty($this->contentIllustartions)) { $this->constructIllustrations(); } $this->content = $this->cleaning($this->content); //$this->content = str_replace('<br />', ' ', $this->content); $this->replaseSR(); $this->forceASCII($this->ncx, $this->opf); $this->ncx = $this->format($this->ncx); $this->opf = $this->format($this->opf); $dirimg = array(); if ($handle = opendir('images/books/' . $this->SID . '/' . $this->BID . '/')) { while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != ".." && $entry != "cover.jpg" && $entry != "cover.jpeg" && $entry != "Cover.jpg" && $entry != "Cover.jpeg" && $entry != "resized") { $dirimg[] = $entry; } } closedir($handle); } $zip = new ZipArchive(); if ($zip->open($this->epub) === TRUE) { $zip->addFromString('OEBPS/Text/Body.xhtml', $this->content); $zip->addFromString('OEBPS/Text/Cover.xhtml', $this->cover); if (!empty($this->contentIllustartions)) { $zip->addFromString('OEBPS/Text/Illustrations.xhtml', $this->illustartions); } $zip->addFromString('OEBPS/toc.ncx', $this->ncx); $zip->addFromString('OEBPS/content.opf', $this->opf); if ($result = $this->searchFolder("images/books/" . $this->SID . "/" . $this->BID . "/*", '/^[Cc]over.jp[e]?g/')) { if ($this->resolution == "original") { $zip->addFile("images/books/" . $this->SID . "/" . $this->BID . "/" . $result, 'OEBPS/Images/Cover.jpg'); } else { try { if (file_exists("images/books/" . $this->SID . "/" . $this->BID . "/resized/" . $this->device[$this->resolution]['h'] . "x" . $this->device[$this->resolution]['w'] . "/" . $result)) { $zip->addFile("images/books/" . $this->SID . "/" . $this->BID . "/resized/" . $this->device[$this->resolution]['h'] . "x" . $this->device[$this->resolution]['w'] . "/" . $result, 'OEBPS/Images/Cover.jpg'); } else { $image = new Imagick("images/books/" . $this->SID . "/" . $this->BID . "/" . $result); $image->adaptiveResizeImage($this->device[$this->resolution]['h'], $this->device[$this->resolution]['w'], TRUE); $image->writeimage("images/books/" . $this->SID . "/" . $this->BID . "/resized/" . $this->device[$this->resolution]['h'] . "x" . $this->device[$this->resolution]['w'] . "/" . $result); $image->clear(); $image->destroy(); $zip->addFile("images/books/" . $this->SID . "/" . $this->BID . "/resized/" . $this->device[$this->resolution]['h'] . "x" . $this->device[$this->resolution]['w'] . "/" . $result, 'OEBPS/Images/Cover.jpg'); } } catch (Exception $e) { $zip->addFile("images/books/" . $this->SID . "/" . $this->BID . "/" . $img, 'OEBPS/Images/' . $img); } } unset($result); } else { $zip->addFile('404.jpg', 'OEBPS/Images/Cover.jpg'); } if (!$this->noImages) { foreach ($dirimg as $img) { if ($this->resolution == "original") { $zip->addFile("images/books/" . $this->SID . "/" . $this->BID . "/" . $img, 'OEBPS/Images/' . $img); } else { $width = $this->device[$this->resolution]['w']; $height = $this->device[$this->resolution]['h']; if (!is_dir("images/books/" . $this->SID . "/" . $this->BID . "/resized")) { mkdir("images/books/" . $this->SID . "/" . $this->BID . "/resized"); } if (!is_dir("images/books/" . $this->SID . "/" . $this->BID . "/resized/" . $this->device[$this->resolution]['h'] . "x" . $this->device[$this->resolution]['w'])) { mkdir("images/books/" . $this->SID . "/" . $this->BID . "/resized/" . $this->device[$this->resolution]['h'] . "x" . $this->device[$this->resolution]['w']); } try { $data = getimagesize("images/books/" . $this->SID . "/" . $this->BID . "/" . $img); $width = $data[0]; $height = $data[1]; if ($width < 400 || $height < 400) { $zip->addFile("images/books/" . $this->SID . "/" . $this->BID . "/" . $img, 'OEBPS/Images/' . $img); } else { if (file_exists("images/books/" . $this->SID . "/" . $this->BID . "/resized/" . $this->device[$this->resolution]['h'] . "x" . $this->device[$this->resolution]['w'] . "/" . $img)) { $zip->addFile("images/books/" . $this->SID . "/" . $this->BID . "/resized/" . $this->device[$this->resolution]['h'] . "x" . $this->device[$this->resolution]['w'] . "/" . $img, 'OEBPS/Images/' . $img); } else { $image = new Imagick("images/books/" . $this->SID . "/" . $this->BID . "/" . $img); $image->adaptiveResizeImage($this->device[$this->resolution]['h'], $this->device[$this->resolution]['w'], TRUE); $image->writeimage("images/books/" . $this->SID . "/" . $this->BID . "/resized/" . $this->device[$this->resolution]['h'] . "x" . $this->device[$this->resolution]['w'] . "/" . $img); $image->clear(); $image->destroy(); $zip->addFile("images/books/" . $this->SID . "/" . $this->BID . "/resized/" . $this->device[$this->resolution]['h'] . "x" . $this->device[$this->resolution]['w'] . "/" . $img, 'OEBPS/Images/' . $img); } } } catch (Exception $e) { $zip->addFile("images/books/" . $this->SID . "/" . $BID . "/" . $img, 'OEBPS/Images/' . $img); } } } } $zip->close(); } else { echo 'Fehler'; } $this->sendFile($this->epub, $this->fileName); }
// // (including any white space before the "<?php" tag) will corrupt the // // image data. Comment out the "header" line to debug any issues. // header("Content-type: image/jpg"); // ImageJpeg($im,__APP_PATH__.'/test.jpg'); // ImageDestroy($im); } //Code to convert from .svg to .png by Image array $fn2 = 'test.svg'; $im = new Imagick(); $svg = file_get_contents($usmap); try { $im->readImageBlob($svg); /*png settings*/ $im->setImageFormat("png24"); $im->resizeImage(720, 445, imagick::FILTER_LANCZOS, 1); /*Optional, if you need to resize*/ /*jpeg*/ $im->setImageFormat("jpeg"); $im->adaptiveResizeImage(720, 445); /*Optional, if you need to resize*/ $im->writeImage(__APP_PATH__ . '/js/testings.png'); /*(or .jpg)*/ $im->clear(); $im->destroy(); } catch (Exception $ex) { print_R($ex); } ?>
/** * Scales the image to a specific width and height * * @param int $w The width * @param int $h The height * @return string The path to the scaled file */ public function scaleTo ($w, $h) { $this->ensureCachedirExists(); $outputFile = Configuration::getOption("partkeepr.images.cache").md5($this->getFilename().$w."x".$h).".png"; if (file_exists($outputFile)) { return $outputFile; } $image = new \Imagick(); $image->readImage($this->getFilename()); $image->adaptiveResizeImage($w, $h); $image->writeImage($outputFile); $cachedImage = new CachedImage($this, $outputFile); PartKeepr::getEM()->persist($cachedImage); return $outputFile; }
/** * Add watermark to image * @param string $watermarkPath Path to watermark image * @param string $xPos Horizontal position - 'left', 'right' or 'center' * @param string $yPos Vertical position - 'top', 'bottom' or 'center' * @param bool|int|string $xSize Horizontal watermark size: 100, '50%', 'auto' etc. * @param bool|int|string $ySize Vertical watermark size: 100, '50%', 'auto' etc. * @param bool $xOffset * @param bool $yOffset * @return Imagick * @throws Exception */ public function watermark($watermarkPath, $xPos, $yPos, $xSize = false, $ySize = false, $xOffset = false, $yOffset = false) { $watermark = new \Imagick($watermarkPath); // resize watermark $newSizeX = false; $newSizeY = false; if ($xSize !== false) { if (is_numeric($xSize)) { $newSizeX = $xSize; } elseif (is_string($xSize) && substr($xSize, -1) === '%') { $float = str_replace('%', '', $xSize) / 100; $newSizeX = $this->width * (double) $float; } } if ($ySize !== false) { if (is_numeric($ySize)) { $newSizeY = $ySize; } elseif (is_string($ySize) && substr($ySize, -1) === '%') { $float = str_replace('%', '', $ySize) / 100; $newSizeY = $this->height * (double) $float; } } if ($newSizeX !== false && $newSizeY !== false) { $watermark->adaptiveResizeImage($newSizeX, $newSizeY); } elseif ($newSizeX !== false && $newSizeY === false) { $watermark->adaptiveResizeImage($newSizeX, 0); } elseif ($newSizeX === false && $newSizeY !== false) { $watermark->adaptiveResizeImage(0, $newSizeY); } $startX = false; $startY = false; $watermarkSize = $watermark->getImageGeometry(); if ($yPos === 'top') { $startY = 0; if ($yOffset !== false) { $startY += $yOffset; } } elseif ($yPos === 'bottom') { $startY = $this->height - $watermarkSize['height']; if ($yOffset !== false) { $startY -= $yOffset; } } elseif ($yPos === 'center') { $startY = $this->height / 2 - $watermarkSize['height'] / 2; } else { throw new \Exception('Param $yPos should be "top", "bottom" or "center" insteed "' . $yPos . '"'); } if ($xPos === 'left') { $startX = 0; if ($xOffset !== false) { $startX += $xOffset; } } elseif ($xPos === 'right') { $startX = $this->width - $watermarkSize['width']; if ($xOffset !== false) { $startX -= $xOffset; } } elseif ($xPos === 'center') { $startX = $this->width / 2 - $watermarkSize['width'] / 2; } else { throw new \Exception('Param $xPos should be "left", "right" or "center" insteed "' . $xPos . '"'); } $this->image->compositeImage($watermark, \Imagick::COMPOSITE_OVER, $startX, $startY); return $this; }
function admin_gallery_create() { // Require admin login if(!(isset($_SESSION['active_user']) && $_SESSION['active_user']['type'] == 'admin')) redirect_to('/'); $this->load_outer_template('admin'); if(!isset($this->params[2]) || (!is_numeric($this->params[2]))) throw new exception("No set specified"); $item = $this->params[2]; //$m_gallery = instance_model('gallery'); $m_member = instance_model('members'); $m_set = instance_model('gallery_set'); //$gallery = $m_gallery->get_in_set($item); $set = $m_set->get_by_id($item); if($set == array()) throw new exception('Set does not exist'); $member = $m_member->get_by_id($set[0]['Owner']); if($member == array()) throw new exception('Owning member does not exist'); $title = ''; if(isset($_POST['Submit'])) { $file_name = $_FILES['file']['name']; $file_mime = $_FILES['file']['type']; $error = false; if(!in_array(strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION)), $GLOBALS['allowed_ext'])) { $error = true; new_flash('File type is not allowed',1); } $is_image = false; $unique_id = sha1(time()); $tmppath = TMPFILES . '/' . $unique_id . '_' . $_FILES['file']['name']; if(isset($_FILES['file']) && move_uploaded_file($_FILES['file']['tmp_name'], $tmppath)) { // preprocess images try { $is_image = true; $im = new Imagick($tmppath); $im->adaptiveResizeImage('620','620', true); $im->writeImage($tmppath); $im->destroy(); } // Handle outher file types catch(exception $e){ $error = true; new_flash('Could not read file',1); } } else { $error = true; new_flash('File failed to upload',1); } if($error == false) { if(!file_exists('res/gallery/' . $member[0]['Clean_title'])) mkdir('res/gallery/' . $member[0]['Clean_title']); if(!file_exists('res/gallery/' . $member[0]['Clean_title'] . '/thumbs')) mkdir('res/gallery/' . $member[0]['Clean_title'] . '/thumbs'); // move image file $newloc = 'res/gallery/' . $member[0]['Clean_title']; $hard_file_name = $file_name; $ctr = 0; for(;;) { if($ctr > 200) throw new exception('Could not create unique file name'); if(file_exists($newloc . '/' . $hard_file_name)) { $ctr += 1; // add number to file name $split_name = explode('.', $file_name); $base = array_shift($split_name); $ext = implode('.', $split_name); $hard_file_name = $base . '_' . $ctr . '.' . $ext; } else break; } $file_name = $hard_file_name; // move file rename($tmppath, $newloc . '/' . $file_name); // generate thumbnail $im = new Imagick($newloc . '/' . $file_name); $im->cropThumbnailImage('130','98'); $im->writeImage($newloc . '/thumbs/' . $file_name); $im->destroy(); $m_gallery = instance_model('gallery'); $m_gallery->create($item, $file_name); redirect_to(make_url('members', 'admin_gallery', $item)); } } $view = instance_view('files/admin/upload'); $view = $view->parse_to_variable(array( 'form_url' => make_url('members', 'admin_gallery_create', $item), 'back_url' => make_url('members', 'admin_gallery', $item), 'title' => 'Upload image' )); $this->set_template_paramiters(array( 'content' => $view )); }