public function serverAction(Request $request) { $fileName = $request->get('fileName'); $points = $request->get('transform'); $sizes = $this->getSizes(); $fileFullName = $sizes[0]['dir'] . $fileName; try { $image = new \Imagick($fileFullName); } catch (\ImagickException $e) { return new JsonResponse(array('success' => false, 'errorMessage' => 'На сервере не найден файл')); } $finalScale = $sizes[0]['width'] / $sizes[0]['mediumWidth']; for ($i = 0; $i <= 5; $i++) { $points[$i] *= $finalScale; } $image->distortImage(\Imagick::DISTORTION_AFFINEPROJECTION, $points, TRUE); $image->cropImage($sizes[0]['width'], $sizes[0]['height'], 0, 0); $hashFile = md5_file($fileFullName); $fileName = $hashFile . '.jpg'; foreach ($sizes as $size) { $imgFullName = $size['dir'] . $fileName; $image->thumbnailImage($size['width'], $size['height'], TRUE); $image->writeimage($imgFullName); if (!file_exists($imgFullName)) { $image->writeimage($imgFullName); } } return new JsonResponse(array('success' => true, 'fileName' => $fileName)); }
public function createThali($dishArray = array(), $is_thali, $w = 140, $h = 0) { Configure::write('debug', 2); ini_set("max_execution_time", -1); $thali1 = new Imagick("tmpl/img/thali-1.png"); $thali2 = new Imagick("tmpl/img/thali-2.png"); $thali3 = new Imagick("tmpl/img/thali-3.png"); $mask_1 = new Imagick("tmpl/img/thali-mask2.png"); $mask_2 = new Imagick("tmpl/img/thali-mask3.png"); if (!is_array($dishArray)) { return false; } $mask_cnt = 0; foreach ($dishArray as $dish) { if ($mask_cnt > 1) { // Mask Locking (Modify if masks will be increased or decreased) break; } $dish = new Imagick($dish); $dish->scaleimage($thali1->getimagewidth(), $thali1->getimageheight()); // Set As per bowl image if ($is_thali) { if ($mask_cnt == 1) { $dish->rotateimage("#fff", 180); } $dish->compositeimage(new Imagick("tmpl/img/thali-mask" . ($mask_cnt + 2) . ".png"), \Imagick::COMPOSITE_COPYOPACITY, 0, 0, Imagick::CHANNEL_ALPHA); $dish->mergeimagelayers(Imagick::LAYERMETHOD_COALESCE); $thali1->compositeimage($dish, \Imagick::COMPOSITE_ATOP, 0, 0, Imagick::CHANNEL_ALPHA); $thali1->mergeimagelayers(Imagick::LAYERMETHOD_COALESCE); $thali2->compositeimage($dish, \Imagick::COMPOSITE_ATOP, 0, 0, Imagick::CHANNEL_ALPHA); $thali2->mergeimagelayers(Imagick::LAYERMETHOD_COALESCE); $thali3->compositeimage($dish, \Imagick::COMPOSITE_ATOP, 0, 0, Imagick::CHANNEL_ALPHA); $thali3->mergeimagelayers(Imagick::LAYERMETHOD_COALESCE); } else { $thali3 = $dish; } $mask_cnt++; } $url = "files/thali_images/" . $this->randomString(6); $url_end = "-Thali.jpg"; $result_urls = array(); $thali1->setimageformat("jpg"); $thali1->setImageFileName($result_urls[] = $url . "-0" . $url_end); $thali1->scaleimage($w, $h); if ($is_thali) { $thali2->writeimage(); } $thali1->destroy(); $thali2->setimageformat("jpg"); $thali2->setImageFileName($result_urls[] = $url . "-1" . $url_end); $thali2->scaleimage($w, $h); if ($is_thali) { $thali2->writeimage(); } $thali2->destroy(); $thali3->setimageformat("jpg"); $thali3->setImageFileName($result_urls[] = $url . "-2" . $url_end); $thali3->scaleimage($w, $h); $thali3->writeimage(); $thali3->destroy(); return $result_urls; }
/** * @param integer $x * @param integer $y * @param integer $width * @param integer $height * * @return boolean */ public function crop($x, $y, $width, $height) { try { $this->imagick->cropimage($width, $height, $x, $y); $this->imagick->writeimage($this->pathToUploadDir . $this->file->getPath()); $this->file->getParams()->setWidth($width); $this->file->getParams()->setHeight($height); $this->entityManager->flush(); return true; } catch (\Exception $exception) { return false; } }
public function setBackground($file) { if (empty($this->pdf)) { die('Set layout before'); } if (!is_file($file)) { die('Incorect background file'); } $tmp = $this->getTmpFilePath('pdf'); $img = new Imagick($file); $img->resizeimage(1076, 720, Imagick::FILTER_LANCZOS, 1); $img->setresolution(300, 300); $img->setimageformat('pdf'); $img->writeimage($tmp); $this->pdf->setSourceFile($tmp); $this->pdf->SetMargins(0, 0, 0, true); $tplIdx = $this->pdf->importPage(1); $this->pdf->useTemplate($tplIdx, null, null, 0, 0, true); $this->pdf->SetMargins(0, 0, 0, true); $this->pdf->setCellHeightRatio(1); $this->pdf->setCellPaddings(0, 0, 0, 0); $this->pdf->setCellMargins(1, 1, 1, 1); $this->pdf->SetAutoPageBreak(false); $this->pdf->SetPrintHeader(false); $this->pdf->SetPrintFooter(false); }
public static function cropImage($dataPathRoot, $imageFileRelativeName, $imageThumbFileRelativeName, $width, $height) { $cloudStorage = CloudHelper::getCloudModule(CloudHelper::CLOUD_MODULE_STORAGE); $tempSrcFilePath = $cloudStorage->createTempFileForStorageFile($dataPathRoot, $imageFileRelativeName); $tempDestFilePath = $cloudStorage->getTempFilePath(); //生成缩略图 if (extension_loaded('imagick')) { // 如果有 imagick 模块,优先选择 imagick 模块,因为生成的图片质量更高 $img = new \Imagick($tempSrcFilePath); $img->stripimage(); //去除图片信息 $img->setimagecompressionquality(95); //保证图片的压缩质量,同时大小可以接受 $img->cropimage($width, $height, 0, 0); $img->writeimage($tempDestFilePath); $cloudStorage->moveFileToStorage($dataPathRoot, $imageThumbFileRelativeName, $tempDestFilePath); //主动释放资源,防止程序出错 $img->destroy(); unset($img); } else { // F3 框架的 Image 类限制只能操作 UI 路径中的文件,所以我们这里需要设置 UI 路径 global $f3; $f3->set('UI', dirname($tempSrcFilePath)); $img = new \Image('/' . basename($tempSrcFilePath)); $img->resize($width, $height, true); $img->dump('jpeg', $tempDestFilePath); $cloudStorage->moveFileToStorage($dataPathRoot, $imageThumbFileRelativeName, $tempDestFilePath); //主动释放资源,防止程序出错 $img->__destruct(); unset($img); } // 删除临时文件 @unlink($tempSrcFilePath); @unlink($tempDestFilePath); }
public function property() { $im = new Imagick(); $im->newimage(50, 50, 'blue'); $im->setimageformat('jpg'); $im->setimageproperty('comment', 'rawr'); var_dump($im->getimageproperty('comment')); $im->writeimage(getcwd() . '/images/test/output.jpg'); echo '<br />' . var_dump($im->getimageproperty('comment')); echo '<img src="/images/test/output.jpg" /><br />'; $this->read(); }
public function start() { //var_dump($this->filename, $this->uploadfile); if (move_uploaded_file($this->tmpfilename, $this->uploadfile)) { $img = new Imagick($this->uploadfile); $img->resizeimage($this->h, $this->w, Imagick::FILTER_LANCZOS, 1); $img->writeimage($this->uploadfile); $img->destroy(); return $this->uploaddir . $this->filenewname; } //echo 'not found'; return false; }
protected static function convertPDF($file) { if ("%PDF-" === file_get_contents($file, null, null, 0, 5)) { // magic! if (class_exists('Imagick')) { $img = new \Imagick($file . '[0]'); $img->setimageformat("jpg"); $img->writeimage($file); } else { exec(sprintf('convert %s[0] %s', escapeshellarg($file), escapeshellarg($file . '.jpg'))); rename($file . '.jpg', $file); } } }
public function storeCover(BookInterface $book, $cover) { #/conifg/filesystems.php $ebook_path = "{$book->id}/Resources/Templates/ebook/cover.jpg"; $print_path = storage_path("books/{$book->id}/Resources/Templates/print"); Storage::disk('book_local')->put($ebook_path, File::get($cover)); Storage::disk('book_local')->put("{$book->id}/Resources/Templates/cover.jpg", File::get($cover)); if (!is_dir($print_path)) { mkdir($print_path, 0775, true); // argumento true criar pastas recursivamente } $img = new \Imagick($ebook_path); $img->setimageformat("pdf"); $img->writeimage($print_path . '/cover.pdf'); }
function pdfthumb($src) { if (!$src || !file_exists(realpath($src))) { return ''; } $infos = pathinfo(realpath($src)); $cachedFile = 'application/cache/pdfsthumbs/' . str_replace('/', '-', str_replace(realpath(BASEPATH . '/../') . '/', '', $infos['dirname'] . '/' . $infos['filename'])) . '.png'; if (file_exists($cachedFile)) { return $cachedFile; } $source = realpath($src); $im = new Imagick($source); $im->setiteratorindex(0); $im->setcompressionquality(90); $im->writeimage($cachedFile); return $cachedFile; }
function renderCustomBitDepthPNG() { $imagePath = $this->control->getImagePath(); $imagick = new \Imagick(realpath($imagePath)); $imagick->setImageFormat('png'); $imagick->setOption('png:bit-depth', '16'); $imagick->setOption('png:color-type', 6); header("Content-Type: image/png"); $crash = true; if ($crash) { echo $imagick->getImageBlob(); } else { $tempFilename = tempnam('./', 'imagick'); $imagick->writeimage(realpath($tempFilename)); echo file_get_contents($tempFilename); } }
/** * Resizes an image image * @return boolean */ public function resize() { try { // Create new Image object // $im = new Imagick($this->image->get('image_path')); // Resize the image // $im->scaleimage($this->image->get('height'), $this->image->get('width')); // Grab the output from writing the image to disk // $return = $im->writeimage($this->image->get('resized_path')); // Clean up memory // $im->clear(); $im->destroy(); // $return only returns true if image is written // return $return ? true : false; } catch (Exception $e) { $this->log->exceptionLog($e, __METHOD__); } }
protected function parseItems($xpath, $html, &$items) { $crawler = new Crawler(); $crawler->addHtmlContent($html); foreach ($crawler->filterXPath($xpath) as $tr) { $item = array(); $tds = $tr->getElementsByTagName('td'); if (0 == $tds->length) { continue; } $item['id'] = (int) ($item['value'] = str_replace(array("\n", "'"), '', $tds->item(1)->nodeValue)); $name = $tds->item(3); $sup = $name->getElementsByTagName('sup')->item(0); if (null !== $sup) { $name->removeChild($sup); } $item['name'] = $item['label'] = str_replace(array("\n", "'"), '', $name->nodeValue); /** @var \DOMElement $tds */ if ($tds->item(4)->getElementsByTagName('a')->length > 0) { $title = $tds->item(4)->getElementsByTagName('a')->item(0)->getAttribute('title'); } else { continue; } $item['title'] = $title; if ($tds->item(0)->childNodes->length != 0 && $tds->item(0)->childNodes->item(0)->nodeName == 'a' && $tds->item(0)->childNodes->item(0)->childNodes->item(0)->nodeName == 'img') { $image = file_get_contents($tds->item(0)->childNodes->item(0)->childNodes->item(0)->getAttribute('src')); $storepath = sprintf('/var/www/MControl/images/%s.png', str_replace(':', '_', $item['name'])); /** @var \Imagick $croppedImage */ $croppedImage = new \Imagick(); $croppedImage->readimageblob($image); $croppedImage->cropimage(25, 12, 0, 0); $croppedImage->writeimage($storepath); $palette = $this->colorPalette($storepath, 2); $item['color'] = str_split($palette[1], 2); } else { $item['color'] = null; } $items[] = $item; } return $items; }
public function uploaderAction(Request $request) { // Получение переданных файлов и информации об альбоме из запроса $file = $_FILES['uploadedImages']; $tmpFileName = $file['tmp_name']; if (is_uploaded_file($tmpFileName)) { chmod($tmpFileName, 0660); } $albumID = $request->get('albumID'); // Создание экземпляра Imagick и образка изображение до нужного размера try { $image = new \Imagick($tmpFileName); } catch (\ImagickException $e) { return new JsonResponse(array('success' => false, 'errorMessage' => ["Файл {$file['tmp_name']} не загрузился"])); } $image->cropImage(800, 800, 0, 0); // Формирование нового имени файла $hashFile = md5_file($tmpFileName); $newFileName = $hashFile . '.jpg'; // Сохранение файла в папки $uploadDir = $request->server->get('DOCUMENT_ROOT') . '/uploaded/images'; $imagePaths = array('800x800' => "{$uploadDir}/800x800/", '200x200' => "{$uploadDir}/200x200/"); foreach ($imagePaths as $size => $path) { $dimensions = explode('x', $size); $image->thumbnailImage((int) $dimensions[0], (int) $dimensions[1], true, false); $image->writeimage($path . $newFileName); } // Сохранение информации о файле в базе $em = $this->getDoctrine()->getManager(); $album = $em->getRepository('PhotoBundle:Album')->find($albumID); if (!$album) { return new JsonResponse(array('success' => false, 'errorMessage' => ["Переданы не корректные парраметры"])); } $photo = new Photo(); $photo->setAlbum($album)->setEnabled(1)->setName($newFileName); $em->persist($photo); $em->flush(); $images = array('success' => true, 'fileName' => $newFileName); //$images = ''; return new JsonResponse($images); }
public function beforeSave($options = array()) { Configure::write('debug', 2); parent::beforeSave($options); if (isset($this->data[$this->alias]['cash_by_promo'])) { if ($this->data[$this->alias]['cash_by_promo'] > 120) { unset($this->data[$this->alias]['cash_by_promo']); //HackPreventions } } if (isset($this->data[$this->alias]['password'])) { $this->data[$this->alias]['v_code'] = $this->data[$this->alias]['password']; $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']); } if (isset($this->data[$this->alias]['image'])) { App::uses("HtmlHelper", "View/Helper"); $html = new HtmlHelper(new View()); if (isset($this->data[$this->alias]['image']['name'])) { if (isset($this->data[$this->alias]['image']['size'])) { if (isset($this->data[$this->alias]['id'])) { $fx = $this->find("first", array("contain" => false, "conditions" => array("Customer.id" => $this->data[$this->alias]['id']))); $fn = ltrim($fx[$this->alias]['image'], "https://www.pickmeals.com/"); @unlink($fn); } $ext = pathinfo($this->data[$this->alias]['image']['name'], PATHINFO_EXTENSION); $image_name = date('YmdHis') . rand(1, 999) . "." . $ext; $path = $this->data[$this->alias]['image']['tmp_name']; $this->data[$this->alias]['image'] = $html->url("/files/profile_image/" . $image_name, true); $destination = "files/profile_image/" . $image_name; move_uploaded_file($path, $destination); $im = new Imagick($destination); $im->scaleimage(800, 0); $im->writeimage($destination); $im->destroy(); } } } return TRUE; }
function createBowl($dishUrl = null, $w = 140, $h = 0) { $du = explode("/", $dishUrl); $du = explode(".", $du[count($du) - 1]); $uri = $du[count($du) - 2]; $bowl = new Imagick("img/bowl.png"); $mask = new Imagick("img/mask.png"); $dish = new Imagick($dishUrl); $dish->scaleimage($bowl->getimagewidth(), $bowl->getimageheight()); // Set As per bowl image $dish->compositeimage(new Imagick("img/mask.png"), \Imagick::COMPOSITE_COPYOPACITY, 0, 0, Imagick::CHANNEL_ALPHA); $dish->mergeimagelayers(Imagick::LAYERMETHOD_COALESCE); $bowl->compositeimage($dish, \Imagick::COMPOSITE_ATOP, 0, 0, Imagick::CHANNEL_ALPHA); $bowl->mergeimagelayers(Imagick::LAYERMETHOD_COALESCE); $bowl->setimageformat("jpg"); $bowl->setImageFileName($url = "gen/" . $uri . ".jpg"); // $bowl->setinterlacescheme(\Imagick::INTERLACE_PNG); $bowl->scaleimage($w, $h); $bowl->writeimage(); $bowl->destroy(); return $url; }
/** * @param $fileArray * @param bool $create_thumb * @param $destination // relative to app/public/files directory, no trailing slash * @return bool|string */ public function saveImage($fileArray, $create_thumb = false, $destination = false) { $tmp_file = $fileArray['tmp_name']; $name = $fileArray['name']; if (!$destination) { $dest = $this->dest; } else { $dest = $this->dest . DS . $destination; } $img = new \Imagick($tmp_file); $img_width = $img->getimagewidth(); $img_height = $img->getimageheight(); if ($this->_height == 'auto' && is_numeric($this->_width) && $img_width > $this->_width) { // resize only width $img->resizeimage($img_width, 0, \Imagick::FILTER_LANCZOS, 1); } elseif ($this->_width == 'auto' && is_numeric($this->_height) && $img_height > $this->_height) { $img->resizeimage(0, $img_height, \Imagick::FILTER_LANCZOS, 1); } elseif (is_numeric($this->_height) && is_numeric($this->_width)) { $img->resizeimage($img_width, $img_height, \Imagick::FILTER_LANCZOS, 1, 1); } #dpi $img->setImageUnits(\Imagick::RESOLUTION_PIXELSPERINCH); $img->setImageResolution($this->_dpi, $this->_dpi); #compression $img->setImageCompressionQuality($this->_compression); $name = substr(md5(microtime()), 0, 4) . $name; $name = str_replace(' ', '', $name); try { $img->writeimage($dest . DS . $name); } catch (\Exception $e) { return false; } if ($create_thumb) { $this->createThumb($tmp_file, $dest . DS . 'thumb_' . $name, $this->_thumb_width, $this->_thumb_height); } return $name; }
/** * @param int $thumbSize * @return null|string * @throws \Exception */ public function getThumb($thumbSize = Image::SMALL_THUMB) { switch ($this->type) { case self::IMAGE_FILETYPE: $ext = $this->getExtension(); $imageId = $this->getId(); $urlPart = Image::imgPath($thumbSize, $imageId, $ext, FileService::FROM_PUBLIC); if (!file_exists($urlPart)) { $originalLocation = $this->getLocation(); $image = new \Imagick($originalLocation); $size = Image::sizeByType($thumbSize); $image->cropThumbnailImage($size['width'], $size['height']); FileService::prepareDir(FileService::PUBLIC_PATH . $urlPart); $image->writeimage(FileService::PUBLIC_PATH . $urlPart); } return $urlPart; case self::AUDIO_FILETYPE: return Audio::audioPath($this->id, $this->getExtension(), FileService::FROM_PUBLIC); case self::VIDEO_FILETYPE: return Video::videoPath($this->id, $this->getExtension(), FileService::FROM_PUBLIC); default: } return null; }
public function save_design() { if ($this->input->post('mode') == 'edit') { $this->db->delete('designs', array('id' => $this->input->post('design_id'))); } $faceMacket = str_replace('http://klever.media/', '', $this->input->post('faceMacket')); $backMacket = str_replace('http://klever.media/', '', $this->input->post('backMacket')); $face = $this->input->post('face'); $back = $this->input->post('back'); // get all fonts $query = $this->db->get('fonts'); $fonts = array(); foreach ($query->result() as $font) { $fonts[$font->family] = $font->source; } // generate pdf face template name and preview name $face_pdf = 'uploads/redactor/face_' . md5(microtime(true)) . '.pdf'; $face_preview = 'uploads/redactor/face_' . md5(microtime(true)) . '.jpg'; // convert face image to pdf $img = new Imagick($faceMacket); $img->setresolution(300, 300); $img->setcolorspace(Imagick::COLORSPACE_CMYK); $img->resizeimage(1076, 720, Imagick::FILTER_LANCZOS, 1); $img->setimageformat('pdf'); $img->writeimage($face_pdf); // include TCPDF ana FPDI include_once APPPATH . 'libraries/tcpdf/tcpdf.php'; include_once APPPATH . 'libraries/tcpdf/fpdi.php'; include_once APPPATH . 'libraries/tcpdf/include/tcpdf_fonts.php'; $fontMaker = new TCPDF_FONTS(); // создаём лист $pdf = new FPDI('L', 'mm', array(91, 61), true, 'UTF-8', false); $pdf->SetMargins(0, 0, 0, true); $pdf->AddPage('L'); // загрузим ранее сохранённый шаблон $pdf->setSourceFile($face_pdf); $pdf->SetMargins(0, 0, 0, true); $tplIdx = $pdf->importPage(1); $pdf->useTemplate($tplIdx, null, null, 0, 0, true); // установим опции для pdf $pdf->setCellHeightRatio(1); $pdf->setCellPaddings(0, 0, 0, 0); $pdf->setCellMargins(0, 0, 0, 0); $pdf->SetAutoPageBreak(false, 0); $pdf->SetPrintHeader(false); $pdf->SetPrintFooter(false); if (!empty($face)) { // отрисуем сначала изображения лица foreach ($face as $item) { if ($item['type'] == 'image') { $pdf->Image($_SERVER['DOCUMENT_ROOT'] . '/' . str_replace('http://klever.media/', '', $item['content']), $this->px_to_mm($item['left']), $this->px_to_mm($item['top']), $this->px_to_mm($item['width']), '', '', '', '', false, 300); } } // потом текст на лице foreach ($face as $item) { if ($item['type'] == 'text') { $cmyk = $this->rgbToCmyk($item['color']); $pdf->SetTextColor($cmyk['c'] * 100, $cmyk['m'] * 100, $cmyk['y'] * 100, $cmyk['k'] * 100); // set font $tcpdfFont = $fontMaker->addTTFfont(realpath('fonts/redactor/' . $fonts[$item['font']])); $pdf->SetFont($tcpdfFont, '', $item['size'] / 2, '', 'false'); $pdf->Text($this->px_to_mm($item['left']), $this->px_to_mm($item['top']), $item['content'], false, false, true, 0, 0, 'L', false, '', 0, false, 'T', 'L', false); } } } // сохраним пдф лица $pdf->Output($_SERVER['DOCUMENT_ROOT'] . '/' . $face_pdf, 'F'); // сделаем превью для пользователя $im = new Imagick(); $im->setResolution(300, 300); $im->readimage($face_pdf . '[0]'); $im->flattenimages(); $im->setImageFormat('jpg'); $im->resizeimage(1076, 720, Imagick::FILTER_LANCZOS, 1); $im->writeImage($face_preview); $im->clear(); $im->destroy(); //exec('$ convert ' . $_SERVER['DOCUMENT_ROOT'] . '/' . $face_pdf . ' ' . $_SERVER['DOCUMENT_ROOT'] . '/' . $face_preview); // есть ли оборот if (!empty($backMacket)) { // generate pdf back template name and preview name $back_pdf = 'uploads/redactor/back_' . md5(microtime(true)) . '.pdf'; $back_preview = 'uploads/redactor/back_' . md5(microtime(true)) . '.jpg'; // convert back image to pdf $img = new Imagick($backMacket); $img->setresolution(300, 300); $img->setcolorspace(Imagick::COLORSPACE_CMYK); $img->resizeimage(1076, 720, Imagick::FILTER_LANCZOS, 1); $img->setimageformat('pdf'); $img->writeimage($back_pdf); // создаём лист $pdf = new FPDI('L', 'mm', array(91, 61), true, 'UTF-8', false); $pdf->AddPage('L'); // загрузим ранее сохранённый шаблон $pdf->setSourceFile($_SERVER['DOCUMENT_ROOT'] . '/' . $back_pdf); $pdf->SetMargins(0, 0, 0, true); $tplIdx = $pdf->importPage(1); $pdf->useTemplate($tplIdx, null, null, 0, 0, true); // установим опции для pdf $pdf->SetMargins(0, 0, 0, true); $pdf->setCellHeightRatio(1); $pdf->setCellPaddings(0, 0, 0, 0); $pdf->setCellMargins(1, 1, 1, 1); $pdf->SetAutoPageBreak(false); $pdf->SetPrintHeader(false); $pdf->SetPrintFooter(false); if (!empty($back)) { // отрисуем сначала изображения оборота foreach ($back as $item) { if ($item['type'] == 'image') { $pdf->Image($_SERVER['DOCUMENT_ROOT'] . '/' . str_replace('http://klever.media/', '', $item['content']), $this->px_to_mm($item['left']), $this->px_to_mm($item['top']), $this->px_to_mm($item['width']), '', '', '', '', false, 300); } } // потом текст на обороте foreach ($back as $item) { if ($item['type'] == 'text') { $cmyk = $this->rgbToCmyk($item['color']); $pdf->SetTextColor($cmyk['c'] * 100, $cmyk['m'] * 100, $cmyk['y'] * 100, $cmyk['k'] * 100); // set font $tcpdfFont = $fontMaker->addTTFfont($_SERVER['DOCUMENT_ROOT'] . '/fonts/redactor/' . $fonts[$item['font']]); $pdf->SetFont($tcpdfFont, '', $item['size'] / 2, '', 'false'); $pdf->Text($this->px_to_mm($item['left']), $this->px_to_mm($item['top']), $item['content'], false, false, true, 0, 0, 'L', false, '', 0, false, 'T', 'L', false); } } } // сохраним пдф оборота $pdf->Output($_SERVER['DOCUMENT_ROOT'] . '/' . $back_pdf, 'F'); // сделаем превью для пользователя $im = new Imagick(); $im->setResolution(300, 300); $im->readimage($back_pdf . '[0]'); $im->setImageFormat('jpg'); $im->flattenimages(); $im->resizeimage(1076, 720, Imagick::FILTER_LANCZOS, 1); $im->writeImage($back_preview); $im->clear(); $im->destroy(); } $this->db->insert('products', array('name' => 'cards_pvc', 'tiraj' => 100, 'weight' => 0.5, 'price' => 0.49, 'cost' => 49, 'macket' => 'my_macket')); $product_id = $this->db->insert_id(); $this->db->insert('designs', array('product_id' => $product_id, 'theme_id' => $this->input->post('theme'), 'face_background' => $faceMacket, 'back_background' => empty($backMacket) ? NULL : $backMacket, 'face' => $face_preview, 'back' => empty($back_preview) ? '' : $back_preview, 'type' => 'system')); $design_id = $this->db->insert_id(); $options = array(); if (!empty($face)) { foreach ($face as $item) { if ($item['type'] == 'text') { $options[] = array('design_id' => $design_id, 'type' => 'text', 'front' => 'face', 'top' => $item['top'], 'left' => $item['left'], 'width' => NULL, 'height' => NULL, 'content' => $item['content'], 'font' => $item['font'], 'color' => $item['color'], 'size' => $item['size']); } else { $options[] = array('design_id' => $design_id, 'type' => 'image', 'front' => 'face', 'top' => $item['top'], 'left' => $item['left'], 'width' => $item['width'], 'height' => $item['height'], 'content' => $item['content'], 'font' => NULL, 'color' => NULL, 'size' => NULL); } } } if (!empty($back)) { foreach ($back as $item) { if ($item['type'] == 'text') { $options[] = array('design_id' => $design_id, 'type' => 'text', 'front' => 'back', 'top' => $item['top'], 'left' => $item['left'], 'width' => NULL, 'height' => NULL, 'content' => $item['content'], 'font' => $item['font'], 'color' => $item['color'], 'size' => $item['size']); } else { $options[] = array('design_id' => $design_id, 'type' => 'image', 'front' => 'back', 'top' => $item['top'], 'left' => $item['left'], 'width' => $item['width'], 'height' => $item['height'], 'content' => $item['content'], 'font' => NULL, 'color' => NULL, 'size' => NULL); } } } if (count($options) > 0) { $this->db->insert_batch('design_options', $options); } echo 'OK'; }
/** * * @param string $dishUrl * @param int $w Width of the Output Image * @param int $h Height of Output Image * @return string Path of genrated Image */ public function createBowl($dishUrl = null, $w = 140, $h = 0) { $bowl = new Imagick("tmpl/img/bowl.png"); $mask = new Imagick("tmpl/img/mask.png"); $dish = new Imagick($dishUrl); $dish->scaleimage($bowl->getimagewidth(), $bowl->getimageheight()); // Set As per bowl image $dish->compositeimage(new Imagick("tmpl/img/mask.png"), \Imagick::COMPOSITE_COPYOPACITY, 0, 0, Imagick::CHANNEL_ALPHA); $dish->mergeimagelayers(Imagick::LAYERMETHOD_COALESCE); $bowl->compositeimage($dish, \Imagick::COMPOSITE_ATOP, 0, 0, Imagick::CHANNEL_ALPHA); $bowl->mergeimagelayers(Imagick::LAYERMETHOD_COALESCE); $bowl->setimageformat("jpg"); $bowl->setImageFileName($url = "img_tmp/" . $this->randomString(10) . "-GE.jpg"); // $bowl->setinterlacescheme(\Imagick::INTERLACE_PNG); $bowl->scaleimage($w, $h); $bowl->writeimage(); $bowl->destroy(); return $url; }
/** * By doing random sampling from the image, find the most energetic point on the passed in * image * * @param \Imagick $image * @return array */ protected function getHighestEnergyPoint(\Imagick $image) { $size = $image->getImageGeometry(); // It's more performant doing random pixel uplook via GD $tmpFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'image' . rand(); $image->writeimage($tmpFile); $im = imagecreatefromjpeg($tmpFile); $xcenter = 0; $ycenter = 0; $sum = 0; // Sample only sample 1/50 of of all the pixels in the image $sampleSize = round($size['height'] * $size['width']) / 50; for ($k = 0; $k < $sampleSize; $k++) { $i = mt_rand(0, $size['width'] - 1); $j = mt_rand(0, $size['height'] - 1); $rgb = imagecolorat($im, $i, $j); $r = $rgb >> 16 & 0xff; $g = $rgb >> 8 & 0xff; $b = $rgb & 0xff; $val = $this->rgb2bw($r, $g, $b); $sum += $val; $xcenter += ($i + 1) * $val; $ycenter += ($j + 1) * $val; } if ($sum) { $xcenter /= $sum; $ycenter /= $sum; } $point = array('x' => $xcenter, 'y' => $ycenter, 'sum' => $sum / round($size['height'] * $size['width'])); return $point; }
function generate_final_video_frames($converted_avatars, $uid, $dir = 'data', $videos_frames) { include get_template_directory() . '/video_libs/libs.php'; $frames = array(); $i = 1; $converted_path = $dir . "/{$uid}/frames"; if (!file_exists("{$converted_path}")) { exec("mkdir -p {$converted_path}"); } exec("chmod 777 -R {$converted_path}"); exec("rm -rf {$converted_path}/*"); #include get_template_directory() . '/video_libs/data.php'; /*include get_template_directory() . '/video_libs/data_live.php'; $videos_frames = get_data_videos($_REQUEST['uid'], $_REQUEST['eid']);*/ foreach ($videos_frames as $key => $value) { $name = generate_filename($i); $filename = $value->imageFrame; $curr_frame = "{$converted_path}/{$name}"; $frames[] = $curr_frame; $text_objs = isset($value->text) ? $value->text : array(); $image_objs = isset($value->imageFace) ? $value->imageFace : array(); if (array_key_exists($filename, $converted_avatars) && !empty($converted_avatars[$filename])) { if (!empty($image_objs)) { foreach ($image_objs as $image_obj) { $order = $image_obj->order; if ($order == 'back') { $msg = exec("convert {$converted_avatars[$filename]} {$filename} -composite {$curr_frame}"); } else { $msg = exec("convert {$filename} {$converted_avatars[$filename]} -composite {$curr_frame}"); } } } } else { exec("cp {$filename} {$curr_frame}"); } $w = 210; if (!empty($text_objs)) { foreach ($text_objs as $text_obj) { $picin = new Imagick($curr_frame); $draw = new ImagickDraw(); $draw->setTextEncoding('utf-8'); $draw->setFillColor("rgba(255, 255, 255, {$text_obj->opacity})"); $draw->setFont($text_obj->font); $draw->setFontSize($text_obj->size); $positions = explode(',', $text_obj->position); //list($lines, $lineHeight)= wordWrapAnnotation($picin, $draw, $text_obj->text, $w-10); if (!empty($text_obj->break) && $text_obj->break == 'yes') { $y = $positions[1]; $line_height = 55; $str = wordwrap($text_obj->text, 19, "\n"); $str_array = explode("\n", $str); foreach ($str_array as $line) { $picin->annotateImage($draw, $positions[0], $y, 0, $line); $y += $line_height; } } else { $picin->annotateImage($draw, $positions[0], $positions[1], 0, $text_obj->text); } //$picin->annotateImage($draw, $positions[0], $positions[1], 0, $text_obj->text); //$picin->annotateImage($draw, $positions[0], $positions[1], 0, $lines); $picin->writeimage($curr_frame); /*if( strpos($filename, '110.png')){ echo '<pre>'; print_r($image_obj); echo '</pre>'; echo 'aaaa';die; }*/ } } $i++; } return $frames; }
public function WritedataImage() { parent::setimageformat($this->format); parent::writeimage($this->save_to, false); }
/** * @param $field * @param $max_width * @param $max_height * @return bool */ public function resize($field, $max_width, $max_height) { if (!class_exists('\\Imagick') || !isset($this->last_uploads[$field][2])) { return true; } $img_path = $this->last_uploads[$field][2]; $img = new \Imagick($img_path); $w = $img->getimagewidth(); $h = $img->getimageheight(); $nw = $w; $nh = $h; if ($w > $max_width) { $nw = $max_width; } if ($h > $max_height) { $nh = $max_height; } if ($nw != $w || $nh != $h) { $img->resizeImage($nw, $nh, \Imagick::FILTER_LANCZOS, 1); } else { return true; } return $img->writeimage($img_path) && $img->destroy(); }
/** * Crops the image and returns a filepath with the location of a temporary * image * @param $file * @param $coords * @return string */ private function cropImage($file, $coords) { $kuber = $this->get('kuber'); //Download the file and create a temporary copy of the original $imgUrl = $kuber->getUrlFromFile($file); $imgFile = '/tmp/' . $file->getFileName(); file_put_contents($imgFile, file_get_contents($imgUrl)); $img = new \Imagick($imgFile); $img->cropimage($coords['w'], $coords['h'], $coords['x'], $coords['y']); $croppedFile = '/tmp/crop-' . $file->getFileName(); $img->writeimage($croppedFile); // Delete the original file unlink($imgFile); return $croppedFile; }
public function custom_design() { $config['upload_path'] = 'uploads/redactor'; $config['allowed_types'] = 'png|jpg|gif|pdf|tif|tiff'; $config['max_size'] = '10000'; $config['encrypt_name'] = true; $config['max_width'] = 1100; $config['max_height'] = 730; $this->load->library('upload', $config); if ($this->upload->do_upload()) { $file = $this->upload->data(); $faceMacket = 'uploads/redactor/' . $file['raw_name'] . '.jpg'; $img = new Imagick($file['full_path']); $img->flattenimages(); $img->setimageformat('jpg'); $img->resizeimage(1076, 720, Imagick::FILTER_LANCZOS, 1); $img->writeimage($faceMacket); $this->db->insert('designs', array('product_id' => NULL, 'face' => $faceMacket, 'back' => '', 'type' => 'user')); $design_id = $this->db->insert_id(); exit(json_encode(array('error' => '', 'design_id' => $design_id))); } else { exit(json_encode(array('error' => $this->upload->display_errors(' ', ' ')))); } }
public static function addWatermark($src_img, $wm_img, $pos='rb', $q=80) { if ($wm_img === false) { $wm_img = cmsConfig::getInstance()->wmark; } if (!$src_img || !$wm_img) { return false; } $size_src = self::getImgInfo($src_img); $size_wm = self::getImgInfo($wm_img); if (!$size_src || !$size_wm) { return false; } if (self::checkImagick() === true) { $image = new Imagick($src_img); $wm = new Imagick($wm_img); $wm->scaleImage($size_src['width']/10, 0); list($X, $Y) = $this->getWatermarkPos($size_src['width'], $size_src['height'], $wm->getImageWidth(), $wm->getImageHeight()); if ($X < 0 || $Y < 0) { return false; } $wm->evaluateImage(Imagick::EVALUATE_MULTIPLY, 0.8, Imagick::CHANNEL_ALPHA); if ($size_src == 'gif') { foreach ($image as $img) { $img->compositeImage($wm, imagick::COMPOSITE_OVER, $X, $Y); } $image->writeimages($src_img); } else { $image->compositeImage($wm, imagick::COMPOSITE_OVER, $X, $Y); $image->writeimage($src_img); } $image->destroy(); $wm->destroy(); } else { $wimage = imagecreatefrompng($wm_img); if ($size_wm['type'] != 'png' || empty($wimage)) { return false; } list($X, $Y) = $this->getWatermarkPos($size_src['width'], $size_src['height'], $size_wm['width'], $size_wm['height']); if ($X < 0 || $Y < 0) { return false; } switch($size_src['type']) { case 'jpg': $image = imagecreatefromjpeg($src_img); break; case 'gif': $image = imagecreatefromgif($src_img); break; case 'png': $image = imagecreatefrompng($src_img); break; default: break; } if (!$image) { return false; } imagecopyresampled($image, $wimage, $X, $Y, 0, 0, $size_wm['width'], $size_wm['height'], $size_wm['width'], $size_wm['height']); switch($size_src['type']) { case 'jpg': imagejpeg($image, $src_img, $q); break; case 'gif': imagegif($image, $src_img); break; case 'png': imagepng($image, $src_img, (9 - round($q*0.09))); break; } imagedestroy($image); imagedestroy($wimage); } return true; }
public static function thumbnail($item, $width = 0, $height = 0, $border = true, $ftname = '', $quality = 95, $scale_up_force = false) { if (is_numeric($item)) { $f = new file(); $f->load($item); $item = $f; } if (!get_class($item) == 'file') { return; } // precondition, the original image file must exist if (!file_exists($item->absolute_path()) || filesize($item->absolute_path()) < 1) { return; } $original = $item->absolute_path(); $thumbnail = ''; $item_id = $item->id; if (!empty($ftname)) { $item_id = $ftname; } else { if (!is_numeric($item_id)) { $item_id = md5($item->id); } } if ($border === true || $border === 'true' || $border === 1) { $border = 1; } else { $border = 0; } // do we have the thumbnail already created for this image? // option A) opaque JPEG FILE $thumbnail_path_jpg = NAVIGATE_PRIVATE . '/' . $item->website . '/thumbnails/' . $width . 'x' . $height . '-' . $border . '-' . $quality . '-' . $item_id . '.jpg'; if (file_exists($thumbnail_path_jpg)) { // ok, a file exists, but it's older than the image file? (original image file has changed) if (filemtime($thumbnail_path_jpg) > filemtime($original)) { // the thumbnail already exists and is up to date $thumbnail = $thumbnail_path_jpg; } } // option B) transparent PNG FILE $thumbnail_path_png = NAVIGATE_PRIVATE . '/' . $item->website . '/thumbnails/' . $width . 'x' . $height . '-' . $border . '-' . $item_id; if (file_exists($thumbnail_path_png)) { // ok, a file exists, but it's older than the image file? (original image file has changed) if (filemtime($thumbnail_path_png) > filemtime($original)) { // the thumbnail already exists and is up to date $thumbnail = $thumbnail_path_png; } } // do we have to create a new thumbnail if (empty($thumbnail) || isset($_GET['force']) || !(file_exists($thumbnail) && filesize($thumbnail) > 0)) { $thumbnail = $thumbnail_path_png; $handle = new upload($original); $size = array('width' => $handle->image_src_x, 'height' => $handle->image_src_y); $handle->image_convert = 'png'; $handle->file_max_size = '512M'; // maximum image size: 512M (it really depends on available memory) // if needed, calculate width or height with aspect ratio if (empty($width)) { if (!empty($size['height'])) { $width = round($height / $size['height'] * $size['width']); } else { $width = NULL; } return file::thumbnail($item, $width, $height, $border, $ftname); } else { if (empty($height)) { if (!empty($size['width'])) { $height = round($width / $size['width'] * $size['height']); } else { $height = NULL; } return file::thumbnail($item, $width, $height, $border, $ftname); } } $handle->image_x = $width; $handle->image_y = $height; if ($size['width'] < $width && $size['height'] < $height) { // the image size is under the requested width / height? => fill around with transparent color $handle->image_default_color = '#FFFFFF'; $handle->image_resize = true; $handle->image_ratio_no_zoom_in = true; $borderP = array(floor(($height - $size['height']) / 2), ceil(($width - $size['width']) / 2), ceil(($height - $size['height']) / 2), floor(($width - $size['width']) / 2)); $handle->image_border = $borderP; if ($scale_up_force) { $handle->image_border = array(); if ($height > width) { $handle->image_ratio_y = true; } else { $handle->image_ratio_x = true; } } $handle->image_border_color = '#FFFFFF'; $handle->image_border_opacity = 0; } else { // the image size is bigger than the requested width / height, we must resize it $handle->image_default_color = '#FFFFFF'; $handle->image_resize = true; $handle->image_ratio_fill = true; } if ($border == 0) { $handle->image_border = false; $handle->image_ratio_no_zoom_in = false; if (!empty($item->focalpoint) && $handle->image_src_x > 0) { $focalpoint = explode('#', $item->focalpoint); $crop = array('top' => 0, 'right' => 0, 'bottom' => 0, 'left' => 0); // calculate how the file will be scaled, by width or by height if ($handle->image_src_x / $handle->image_x > $handle->image_src_y / $handle->image_y) { // Y is ok, now crop extra space on X $ratio = $handle->image_y / $handle->image_src_y; $image_scaled_x = intval($handle->image_src_x * $ratio); $crop['left'] = max(0, round(($image_scaled_x * ($focalpoint[1] / 100) - $handle->image_x / 2) / $ratio)); $crop['right'] = max(0, round(($image_scaled_x * ((100 - $focalpoint[1]) / 100) - $handle->image_x / 2) / $ratio)); } else { // X is ok, now crop extra space on Y $ratio = $handle->image_x / $handle->image_src_x; $image_scaled_y = intval($handle->image_src_y * $ratio); $crop['top'] = max(0, round(($image_scaled_y * ($focalpoint[0] / 100) - $handle->image_y / 2) / $ratio)); $crop['bottom'] = max(0, round(($image_scaled_y * ((100 - $focalpoint[0]) / 100) - $handle->image_y / 2) / $ratio)); } $handle->image_precrop = array($crop['top'], $crop['right'], $crop['bottom'], $crop['left']); } $handle->image_ratio_crop = true; $handle->image_ratio_fill = true; } $handle->png_compression = 9; $handle->process(dirname($thumbnail)); rename($handle->file_dst_pathname, $thumbnail); clearstatcache(true, $thumbnail); if (!file_exists($thumbnail) || filesize($thumbnail) < 1) { return NULL; } // try to recompress the png thumbnail file to achieve the minimum file size, // only if some extra apps are available if (extension_loaded('imagick')) { $im = new Imagick($thumbnail); $image_alpha_range = $im->getImageChannelRange(Imagick::CHANNEL_ALPHA); //$image_alpha_mean = $im->getImageChannelMean(Imagick::CHANNEL_ALPHA); $image_is_opaque = $image_alpha_range['minima'] == 0 && $image_alpha_range['maxima'] == 0; // autorotate image based on EXIF data $im_original = new Imagick($original); $orientation = $im_original->getImageOrientation(); $im_original->clear(); switch ($orientation) { case imagick::ORIENTATION_BOTTOMRIGHT: $im->rotateimage(new ImagickPixel('transparent'), 180); // rotate 180 degrees break; case imagick::ORIENTATION_RIGHTTOP: $im->rotateimage(new ImagickPixel('transparent'), 90); // rotate 90 degrees CW break; case imagick::ORIENTATION_LEFTBOTTOM: $im->rotateimage(new ImagickPixel('transparent'), -90); // rotate 90 degrees CCW break; } // Now that it's auto-rotated, make sure the EXIF data is correct in case the EXIF gets saved with the image! $im->setImageOrientation(imagick::ORIENTATION_TOPLEFT); if (!$image_is_opaque) { $im->setImageFormat('PNG32'); // Force a full RGBA image format with full semi-transparency. $im->setBackgroundColor(new ImagickPixel('transparent')); $im->setImageCompression(Imagick::COMPRESSION_UNDEFINED); $im->setImageCompressionQuality(0); $im->writeimage($thumbnail); } else { $im->setImageFormat('JPG'); // create an OPAQUE JPG file with the given quality (default 95%) $im->setImageCompressionQuality($quality); $im->writeimage($thumbnail_path_jpg); @unlink($thumbnail); $thumbnail = $thumbnail_path_jpg; } } /* if(command_exists('pngquant')) // PNG Optimization: 8 bit with transparency { @shell_exec('pngquant -s1 --ext .pngquant '.$thumbnail); if(file_exists($thumbnail.'.pngquant')) { unlink($thumbnail); rename($thumbnail.'.pngquant', $thumbnail); } } else*/ } clearstatcache(true, $thumbnail); return $thumbnail; }
<?php require __DIR__ . '/include-imagick-functions.php'; $source_image_gif = '../source-images/city-amsterdam.gif'; echo '<a href="' . $source_image_gif . '">original image</a>' . "\n"; echo '<hr>' . "\n\n"; $processed_images_folder = '../processed-images/'; $processed_images_fullpath = realpath($processed_images_folder) . DIRECTORY_SEPARATOR; list($width, $height) = getimagesize($source_image_gif); // watermark png ---------------------------------------------------------------------------- $watermark_path = '../source-images/watermark.png'; echo '<a href="' . $watermark_path . '">watermark</a>'; list($wm_width, $wm_height) = getimagesize($watermark_path); $ImagickWatermark = new \Imagick(realpath($watermark_path)); // ----------------------------------------------------------------------------------------------- $Imagick = new \Imagick(realpath($source_image_gif)); // copy watermark for source gif image and png watermark ----------------------------- $Imagick->compositeImage($ImagickWatermark, \Imagick::COMPOSITE_DEFAULT, 100, 200); // ----------------------------------------------------------------------------------------------- $save_image_link = 'imagick-source-gif-watermarkimage-png.gif'; $save_result = $Imagick->writeimage($processed_images_fullpath . $save_image_link); $Imagick->clear(); $ImagickWatermark->clear(); var_dump($save_result); echo '<a href="' . $processed_images_folder . $save_image_link . '">watermarked image</a>' . "\n"; echo '<br>' . "\n"; echo '<img src="' . $processed_images_folder . $save_image_link . '" alt="" style="width: 900px;">' . "\n"; echo '<hr>' . "\n\n";
/** * @param UploadedFile $file * @param $entityId * @param $partyDir * @throws InvalidUploadedFile * @return array */ private function uploadIcon(UploadedFile $file, $entityId, $partyDir) { if (strpos($file->getMimeType(), 'image/') !== 0) { throw new InvalidUploadedFile('Иконка должна быть картинкой PNG или JPG'); } $filename = $entityId . '_icon.png'; $path = $partyDir . '/' . $filename; $file->move($partyDir, $filename); $im = new \Imagick($path); $im->resizeimage(120, 110, \Imagick::FILTER_UNDEFINED, 1, true); $im->writeimage($path); return array($file, $path); }