/** * Returns true if image has many frames * * @return bool */ protected function multiframe() { if ($this->image) { return $this->image->getNumberImages() > 1; } return false; }
/** * {@inheritdoc} */ public function count() { try { return $this->resource->getNumberImages(); } catch (\ImagickException $e) { throw new RuntimeException('Failed to count the number of layers', $e->getCode(), $e); } }
public function it_should_be_able_to_load_metadata(Filesystem $filesystem, \Imagick $imagick) { $file = new LocalFile($this->file); $imagick->readImage($this->file)->shouldBeCalled(); $imagick->getNumberImages()->willReturn(0); $imagick->identifyImage()->willReturn(['key' => 'value']); $imagick->getImageProperties('*SpotColor*')->willReturn([1]); $imagick->clear()->shouldBeCalled(); $this->getMetadataForFile($file, ['extended' => true])->shouldReturn(['key' => 'value', 'hasSpotColors' => true]); }
protected function _render($type, $quality) { $type = $this->_save_function($type, $quality); $this->im->setImageCompressionQuality($quality); $this->type = $type; $this->mime = image_type_to_mime_type($type); if ($this->im->getNumberImages() > 1 && $type == "gif") { return $this->im->getImagesBlob(); } return $this->im->getImageBlob(); }
private function getPageCount() { $filetype = $this->fileinfo['filetype']; $mime = $this->fileinfo['mime']; // PDFs only for now if ($filetype == 'pdf' && $mime == 'application/pdf') { // http://stackoverflow.com/a/9642701/1064923 $image = new \Imagick(public_path() . '/' . $this->directory['full'] . $this->fileinfo['filename']); $image->pingImage(public_path() . '/' . $this->directory['full'] . $this->fileinfo['filename']); return $image->getNumberImages() / 2; // I have no idea why this is needed } return null; }
public function step3() { Funcs::escapePost(); if ($_FILES['filecover']['type'] == 'application/pdf' && $_FILES['filepages']['type'] == 'application/pdf') { foreach ($_FILES as $key => $item) { $name = explode('/', $item['tmp_name']); $name = $name[count($name) - 1]; $dirfile = $_SERVER['DOCUMENT_ROOT'] . TEMP_DIR . $name; move_uploaded_file($item['tmp_name'], $dirfile); chmod($dirfile, 0777); $_SESSION['iuser']['upload'][$key]['name'] = $item['name']; $_SESSION['iuser']['upload'][$key]['path'] = $dirfile; if ($key == 'filepages') { $imagick = new Imagick($dirfile); $countpage = $imagick->getNumberImages(); $countpage = $countpage + $countpage % 2; $_SESSION['iuser']['upload']['countpage'] = $countpage; } } } }
/** * Return the number of image pages available in the image object. * * @return integer */ public function getImagePageCount() { return $this->_imagick->getNumberImages(); }
/** * Convert an image file into anoher format. * This need Imagick php extension. * * @param string $fileinput Input file name * @param string $ext Format of target file (It is also extension added to file if fileoutput is not provided). * @param string $fileoutput Output filename * @return int <0 if KO, >0 if OK */ function dol_convert_file($fileinput, $ext = 'png', $fileoutput = '') { global $langs; $image = new Imagick(); $ret = $image->readImage($fileinput); if ($ret) { $ret = $image->setImageFormat($ext); if ($ret) { if (empty($fileoutput)) { $fileoutput = $fileinput . "." . $ext; } $count = $image->getNumberImages(); $ret = $image->writeImages($fileoutput, true); if ($ret) { return $count; } else { return -3; } } else { return -2; } } else { return -1; } }
/** * * @param Oops_File $source * @param unknown_type $Scene * return Oops_File_Temporary */ public function make($source, $scene = null) { // 1. Collect source stats if (!$source instanceof Oops_Image_File) { require_once 'Oops/Image/File.php'; $source = new Oops_Image_File($source); } // $source object contains image's width, height and orientation // 2. Get scene specification require_once 'Oops/Image/Preview/Scene.php'; $sceneObject = Oops_Image_Preview_Scene::getInstance($scene); $rotate = $sceneObject->rotate; // 3. Now calculate target image dimensions, rotate angle, etc. // 3.1. First calculate rotation switch ($source->orient) { case 8: $rotate += 90; case 3: $rotate += 90; case 6: $rotate += 90; $rotate = $rotate % 360; } // 3.2. Calculate target image dimensions $sourceWidth = $source->width; $sourceHeight = $source->height; if ($rotate == 90 || $rotate == 270) { $tmp = $sourceWidth; $sourceWidth = $sourceHeight; $sourceHeight = $tmp; } $resizeCoeffX = $this->_config->width / $sourceWidth; $resizeCoeffY = $this->_config->height / $sourceHeight; if (!$this->_config->enlarge) { if ($resizeCoeffX > 1 || $resizeCoeffX <= 0) { $resizeCoeffX = 1; } if ($resizeCoeffY > 1 || $resizeCoeffY <= 0) { $resizeCoeffY = 1; } } if ($this->_config->crop) { // Fit side with maximum resized rate and crop larger side $resizeCoeff = max($resizeCoeffX, $resizeCoeffY); } else { $resizeCoeff = min($resizeCoeffX, $resizeCoeffY); } $resizeWidth = round($resizeCoeff * $sourceWidth); $resizeHeight = round($resizeCoeff * $sourceHeight); // Now we have instructions for source modifications - rotate it, resize it // 3.3 Calculate preview instructions - crop it, fill it, etc $previewWidth = $resizeWidth; $previewHeight = $resizeHeight; $crop = false; if ($this->_config->crop) { if ($resizeWidth > $this->_config->width) { $previewWidth = $this->_config->width; $crop = true; } if ($resizeHeight > $this->_config->height) { $previewHeight = $this->_config->height; $crop = true; } } $fillColor = null; $fill = false; if ($this->_config->fill) { $previewWidth = $this->_config->width; $previewHeight = $this->_config->height; if ($resizeWidth < $previewWidth || $resizeHeight < $previewHeight) { $fillColor = $this->_config->fill; $fill = true; } } $previewPositionX = ($previewWidth - $resizeWidth) / 2; $previewPositionY = ($previewHeight - $resizeHeight) / 2; /* * Now we have instructions: * rotate angle * resize dimensions * whenever to crop * whenever to fill and fill color * And result image width and height */ // Read source image to new Imagick object $mgkSource = new Imagick(); $mgkSource->readImage($source->filename); $framesCount = $mgkSource->getNumberImages(); if (strlen($this->_config->maxFrames)) { $framesCount = min($framesCount, $this->_config->maxFrames); } $backGroundPixel = is_null($fillColor) ? new ImagickPixel() : new ImagickPixel($fillColor); if ($framesCount > 1) { $mgkPreview = $mgkSource->coalesceImages(); if ($rotate) { $mgkPreview->rotateimage($backGroundPixel, $rotate); } foreach ($mgkPreview as $frame) { $frame->thumbnailImage($resizeWidth, $resizeHeight); $frame->setImagePage($previewWidth, $previewWidth, $previewPositionX, $previewPositionY); } $mgkPreview->cropImage($previewWidth, $previewHeight, 0, 0); } else { $mgkSource->resizeImage($resizeWidth, $resizeHeight, Imagick::FILTER_LANCZOS, 1); $mgkPreview = new Imagick(); $mgkPreview->newImage($previewWidth, $previewHeight, $backGroundPixel); $mgkPreview->compositeImage($mgkSource, Imagick::COMPOSITE_OVER, $previewPositionX, $previewPositionY); } $mgkPreview->stripImage(); $previewFile = new Oops_File_Temporary(); $mgkPreview->setImageFormat($mgkSource->getImageFormat()); $mgkPreview->setCompressionQuality($mgkSource->getCompressionQuality()); $mgkPreview->writeImages($previewFile->filename, true); return $previewFile; }
/** * Bulk PDF import * * ## OPTIONS * * <source-dir> * : required, source directory to import PDF files * * <jpeg-compression-quality> * : optional, jpeg compression quality, default 60 * * <jpeg-resolution> * : optional, jpeg resolution, default 300 * * <post-status> * : optional, PDF post status, default "draft" * * <import-pdf-file> * : flag, if set then import PDF file to Wordpress media library * * ## EXAMPLES * * wp pdf-light-viewer bulk-import --source-dir="/path/to/pdfs" * wp pdf-light-viewer bulk-import --source-dir="/path/to/pdfs" --jpeg-compression-quality=60 --jpeg-resolution=300 --post-status=publish --import-pdf-file * * @synopsis --source-dir=<source-dir> [--jpeg-compression-quality=<jpeg-compression-quality>] [--jpeg-resolution=<jpeg-resolution>] [--post-status=<post-status>] [--import-pdf-file] * @subcommand bulk-import */ public function bulk_import($args, $assoc_args) { // options $source_dir = $assoc_args['source-dir']; $jpeg_compression_quality = isset($assoc_args['jpeg-compression-quality']) ? (int) $assoc_args['jpeg-compression-quality'] : 60; $jpeg_resolution = isset($assoc_args['jpeg-resolution']) ? (int) $assoc_args['jpeg-resolution'] : 300; $post_status = isset($assoc_args['post-status']) ? $assoc_args['post-status'] : 'draft'; $import_pdf_file = isset($assoc_args['import-pdf-file']); // check requirements $plugin_title = PdfLightViewer_Plugin::getData('Title'); $requirements_met = PdfLightViewer_Plugin::requirements(true); if (!$requirements_met) { $message = $plugin_title . ': ' . __('requirements not met, please check plugin settings page for more information.', PDF_LIGHT_VIEWER_PLUGIN); WP_ClI::error($message, true); } else { WP_CLI::log($plugin_title . ': ' . __("requirements are met, happy using!", PDF_LIGHT_VIEWER_PLUGIN)); } // check dir if (!is_readable($source_dir) || !is_dir($source_dir)) { WP_CLI::error(__("Source dir doesn't exist or it's not readable", PDF_LIGHT_VIEWER_PLUGIN), true); } else { WP_CLI::log(sprintf(__("Searching PDF files in %s", PDF_LIGHT_VIEWER_PLUGIN), $source_dir)); } // check PDF files $pdf_files = glob($source_dir . '/*.pdf', GLOB_NOSORT); if (empty($pdf_files)) { WP_CLI::error(__("Source dir doesn't contain PDF files", PDF_LIGHT_VIEWER_PLUGIN), true); } else { WP_CLI::log(sprintf(__("%d PDF files found", PDF_LIGHT_VIEWER_PLUGIN), count($pdf_files))); } // start import $pdf_files_count = count($pdf_files); $all_pdfs_progress = new \cli\progress\Bar(__("Processing PDF files", PDF_LIGHT_VIEWER_PLUGIN), $pdf_files_count); foreach ($pdf_files as $pdf_file_path) { // get number of pages $im = new Imagick(); $im->readImage($pdf_file_path); $pdf_pages_number = $im->getNumberImages(); foreach ($im as $_img) { $geometry = $_img->getImageGeometry(); $width = $geometry['width']; $height = $geometry['height']; break; } $im->destroy(); unset($im); $current_pdf_progress = new \cli\progress\Bar(sprintf(__("Processing PDF file %s", PDF_LIGHT_VIEWER_PLUGIN), $pdf_file_path), $pdf_pages_number); // create PDF post $post_id = wp_insert_post(['post_type' => PdfLightViewer_PdfController::$type, 'post_status' => $post_status, 'post_name' => sanitize_title(pathinfo($pdf_file_path, PATHINFO_FILENAME)), 'post_title' => pathinfo($pdf_file_path, PATHINFO_FILENAME)]); if (is_wp_error($post_id)) { WP_CLI::error(sprintf(__("Could not create PDF post: %s", PDF_LIGHT_VIEWER_PLUGIN), $post_id->get_error_message()), false); } else { // save pdf to media library if ($import_pdf_file) { $image_data = file_get_contents($pdf_file_path); $attach_id = PdfLightViewer_Plugin::create_media_from_data(pathinfo($pdf_file_path, PATHINFO_BASENAME), $image_data); update_post_meta($post_id, 'pdf_file_id', $attach_id); } $pdf_upload_dir = PdfLightViewer_Plugin::createUploadDirectory($post_id); $current_page = 1; $ratio = $width / $height; do_action(PDF_LIGHT_VIEWER_PLUGIN . ':before_import', $post_id, $pdf_file_path); update_post_meta($post_id, '_pdf-light-viewer-import-status', PdfLightViewer_PdfController::STATUS_CLI_PROCESSING); update_post_meta($post_id, '_pdf-light-viewer-import-progress', 0); update_post_meta($post_id, '_pdf-light-viewer-import-current-page', $current_page); update_post_meta($post_id, 'pdf-pages-number', $pdf_pages_number); update_post_meta($post_id, 'pdf-page-width', $width); update_post_meta($post_id, 'pdf-page-height', $height); // process pages for ($current_page; $current_page <= $pdf_pages_number; $current_page++) { $page_number = sprintf('%1$05d', $current_page); if (!file_exists($pdf_upload_dir . '/page-' . $page_number . '.jpg')) { try { PdfLightViewer_PdfController::process_pdf_page($post_id, $current_page, $page_number, $pdf_pages_number, $pdf_file_path, $pdf_upload_dir, $jpeg_resolution, $jpeg_compression_quality, $ratio); } catch (Exception $e) { PdfLightViewer_Plugin::log('Import exception: ' . $e->getMessage(), print_r($e, true)); $error = $e->getMessage(); update_post_meta($post_id, '_pdf-light-viewer-import-status', PdfLightViewer_PdfController::STATUS_FAILED); WP_CLI::warning(sprintf(__('Import of PDF %s failed: %s', PDF_LIGHT_VIEWER_PLUGIN), $pdf_file_path, $error), false); } } $current_pdf_progress->tick(); } do_action(PDF_LIGHT_VIEWER_PLUGIN . ':after_import', $post_id, $pdf_file_path); do_action(PDF_LIGHT_VIEWER_PLUGIN . ':finished_import', $post_id, $pdf_file_path); update_post_meta($post_id, '_pdf-light-viewer-import-status', PdfLightViewer_PdfController::STATUS_FINISHED); WP_CLI::success(sprintf(__('Import of PDF %s finished', PDF_LIGHT_VIEWER_PLUGIN), $pdf_file_path)); } $all_pdfs_progress->tick(); } WP_CLI::success(__('Import finished', PDF_LIGHT_VIEWER_PLUGIN)); }
/** * Load a PDF for use on the printer * * @param string $pdfFile The file to load * @param string $pageWidth The width, in pixels, of the printer's output. The first page of the PDF will be scaled to approximately fit in this area. * @param array $range array indicating the first and last page (starting from 0) to load. If not set, the entire document is loaded. * @throws Exception Where Imagick is not loaded, or where a missing file or invalid page number is requested. * @return multitype:EscposImage Array of images, retrieved from the PDF file. */ public static function loadPdf($pdfFile, $pageWidth = 550, array $range = null) { if (!extension_loaded('imagick')) { throw new Exception(__FUNCTION__ . " requires imagick extension."); } /* * Load first page at very low density (resolution), to figure out what * density to use to achieve $pageWidth */ try { $image = new Imagick(); $testRes = 2; // Test resolution $image->setresolution($testRes, $testRes); $image->readimage($pdfFile . "[0]"); $geo = $image->getimagegeometry(); $image->destroy(); $width = $geo['width']; $newRes = $pageWidth / $width * $testRes; /* Load actual document (can be very slow!) */ $rangeStr = ""; // Set to [0] [0-1] page range if $range is set if ($range != null) { if (count($range) != 2 || !isset($range[0]) || !is_integer($range[0]) || !isset($range[1]) || !is_integer($range[1]) || $range[0] > $range[1]) { throw new Exception("Invalid range. Must be two numbers in the array: The start and finish page indexes, starting from 0."); } $rangeStr = "[" . ($range[0] == $range[1] ? $range[0] : implode($range, "-")) . "]"; } $image->setresolution($newRes, $newRes); $image->readImage($pdfFile . "{$rangeStr}"); $pages = $image->getNumberImages(); /* Convert images to Escpos objects */ $ret = array(); for ($i = 0; $i < $pages; $i++) { $image->setIteratorIndex($i); $ep = new EscposImage(); $ep->readImageFromImagick($image); $ret[] = $ep; } return $ret; } catch (ImagickException $e) { // Wrap in normal exception, so that classes which call this do not themselves require imagick as a dependency. throw new Exception($e); } }
/** * Convert file to image * @param file Input file name * @param ext Extension of target file */ function dol_convert_file($file,$ext='png') { global $langs; $image=new Imagick(); $ret = $image->readImage($file); if ($ret) { $ret = $image->setImageFormat($ext); if ($ret) { $count = $image->getNumberImages(); $ret = $image->writeImages( $file . "." . $ext, true ); if ($ret) return $count; else return -3; } else { return -2; } } else { return -1; } return 1; }
/** * Build source image data (special for Image Magick). * * @param string $source_image_path Path to source image. * @return boolean Return true on success, false on failed. Call to status_msg property to see the details on failure. */ protected function buildSourceImageData($source_image_path) { if ($this->source_image_data == null) { parent::buildSourceImageData($source_image_path); } if ($this->status == false && $this->status_msg != null) { return false; } $Imagick = new \Imagick(realpath($source_image_path)); $i = $Imagick->getNumberImages(); $this->source_image_frames = $i; $this->source_image_data = array_merge($this->source_image_data, array('frames' => $i)); $Imagick->clear(); unset($i, $Imagick); return true; }
} } } if (isset($img)) { $useZga = false; if ($fileType == "image/gif") { $transparentPixels = array(); $transparentMask = array('0', '0', '0', '0'); exec("timeout 5 convert " . $_FILES["imagefile"]["tmp_name"] . "[0-3] -format '%[fx:int(255*p{10,10}.a)]' info:", $transparentPixels); if ($transparentPixels == $transparentMask) { // top left pixels are transparent => gif is transparent => don't do it again unset($sizes[8]); unset($files[8]); } else { $frameRate = $img->getImageDelay(); $frameCount = $img->getNumberImages(); if ($frameRate == 0) { $frameRate = 10; } $metadata = $img->getImageWidth() . "_" . $img->getImageHeight() . "_" . $img->getNumberImages() . "_" . $frameRate; $fileNames[8] = "zga_" . $metadata . "_" . $filePrefix . ".jpg"; $time = microtime(true) - $start; $app['monolog']->addDebug("{$time} Calling montage"); $v = exec(" timeout 15 montage " . $_FILES["imagefile"]["tmp_name"] . " -coalesce -tile x1111 -frame 0 -geometry '+0+0' -quality 80 -colors 256 -background none -bordercolor none /tmp/media/" . $fileNames[8]); $time = microtime(true) - $start; $app['monolog']->addDebug("{$time} Called montage"); $useZga = file_exists("/tmp/media/" . $fileNames[8]); if ($useZga) { $zgaSize = filesize("/tmp/media/" . $fileNames[8]); $originalGifSize = filesize($_FILES["imagefile"]["tmp_name"]); $useZga = $originalGifSize > $zgaSize;
private function extractPages() { // Nome base para os ficheiros extraídos $basename = $this->basedir . '/' . pathinfo($this->filename)['filename'] . '-PDF-%03d.png'; $this->logger->info('Basename: ' . $basename); $im = new \Imagick(); //$im->setResolution(300, 300); $im->setResolution(150, 150); //$im->setResolution(200, 200); $im->readImageBlob(file_get_contents($this->filename)); $this->logger->info('Cargando: ' . $this->filename); $num_pages = $im->getNumberImages(); $this->logger->info('Total enquisas a procesar: ' . $num_pages); $pages = array(); for ($i = 0; $i < $num_pages; $i++) { $im->setIteratorIndex($i); $im->setImageFormat('png'); $filename = sprintf($basename, $i); $this->logger->info('Gardando...: ' . $filename); $im->writeImage($filename); $this->logger->info('Imaxe da enquisa ' . $i . '/' . $num_pages . ' gardada en ' . $filename); $pages[] = $filename; } $im->destroy(); return $pages; }
/** * Load a PDF for use on the printer * * @param string $pdfFile The file to load * @param string $pageWidth The width, in pixels, of the printer's output. The first page of the PDF will be scaled to approximately fit in this area. * @param array $range array indicating the first and last page (starting from 0) to load. If not set, the entire document is loaded. * @throws Exception Where Imagick is not loaded, or where a missing file or invalid page number is requested. * @return multitype:EscposImage Array of images, retrieved from the PDF file. */ public static function loadPdf($pdfFile, $pageWidth = 550) { if (!extension_loaded('imagick')) { throw new Exception(__FUNCTION__ . " requires imagick extension."); } /* * Load first page at very low density (resolution), to figure out what * density to use to achieve $pageWidth */ try { $image = new \Imagick(); $testRes = 2; // Test resolution $image->setresolution($testRes, $testRes); /* Load document just to measure geometry */ $image->readimage($pdfFile); $geo = $image->getimagegeometry(); $image->destroy(); $width = $geo['width']; $newRes = $pageWidth / $width * $testRes; /* Load entire document in */ $image->setresolution($newRes, $newRes); $image->readImage($pdfFile); $pages = $image->getNumberImages(); /* Convert images to Escpos objects */ $ret = array(); for ($i = 0; $i < $pages; $i++) { $image->setIteratorIndex($i); $ep = new EscposImage(); $ep->readImageFromImagick($image); $ret[] = $ep; } return $ret; } catch (\ImagickException $e) { // Wrap in normal exception, so that classes which call this do not themselves require imagick as a dependency. throw new Exception($e); } }
public function joinArchiveContents($pa_files, $pa_options = array()) { if (!is_array($pa_files)) { return false; } $vs_archive_original = tempnam(caGetTempDirPath(), "caArchiveOriginal"); @rename($vs_archive_original, $vs_archive_original . ".tif"); $vs_archive_original = $vs_archive_original . ".tif"; $vo_orig = new Imagick(); foreach ($pa_files as $vs_file) { if (file_exists($vs_file)) { $vo_imagick = new Imagick(); if ($vo_imagick->readImage($vs_file)) { $vo_orig->addImage($vo_imagick); } } } if ($vo_orig->getNumberImages() > 0) { if ($vo_orig->writeImages($vs_archive_original, true)) { return $vs_archive_original; } } return false; }
/** * Copies an image canvas * * @param Imagick $imgCanvas destination canvas * @param Imagick $img source canvas * @param int $dest_x destination x * @param int $dest_y destination y * @param int $src_x source x * @param int $src_y source y * @param int $w width * @param int $h height * @return bool */ function zp_copyCanvas($imgCanvas, $img, $dest_x, $dest_y, $src_x, $src_y, $w, $h) { $img->cropImage($w, $h, $src_x, $src_y); $result = true; for ($i = 0; $result && $i <= $imgCanvas->getNumberImages(); $i++) { $result = $imgCanvas->compositeImage($img, Imagick::COMPOSITE_OVER, $dest_x, $dest_y); $imgCanvas->previousImage(); } return $result; }
/** * Resamples an image to a new copy * * @param Imagick $dst_image * @param Imagick $src_image * @param int $dst_x * @param int $dst_y * @param int $src_x * @param int $src_y * @param int $dst_w * @param int $dst_h * @param int $src_w * @param int $src_h * @return bool */ function zp_resampleImage($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) { foreach ($src_image->getImageProfiles() as $name => $profile) { $dst_image->profileImage($name, $profile); } $result = true; $src_image = $src_image->coalesceImages(); foreach ($src_image as $frame) { $frame->cropImage($src_w, $src_h, $src_x, $src_y); $frame->setImagePage(0, 0, 0, 0); } $src_image = $src_image->coalesceImages(); foreach ($src_image as $frame) { $frame->resizeImage($dst_w, $dst_h, Imagick::FILTER_LANCZOS, 1); $dst_image->setImageDelay($frame->getImageDelay()); $result &= $dst_image->compositeImage($frame, Imagick::COMPOSITE_OVER, $dst_x, $dst_y); if ($dst_image->getNumberImages() < $src_image->getNumberImages()) { $result &= $dst_image->addImage(zp_createImage($dst_image->getImageWidth(), $dst_image->getImageHeight())); } if (!$result) { break; } } return $result; }
function getpdfpage($document) { $im = new Imagick(); $im->pingImage($document); return $im->getNumberImages(); }
public function run($pdf, $opts) { // catch objects if (!isset($opts)) { $opts = ''; } // get options $opts = json_decode($opts); // set up an object if (!$opts) { $opts = (object) array(); } // default options if (!property_exists($opts, 'nocache')) { $opts->nocache = false; } if (!property_exists($opts, 'pagemaxwidth')) { $opts->pagemaxwidth = 1000; } if (!property_exists($opts, 'pagemaxheight')) { $opts->pagemaxheight = 1000; } if (!property_exists($opts, 'thumbmaxwidth')) { $opts->thumbmaxwidth = 100; } if (!property_exists($opts, 'thumbmaxheight')) { $opts->thumbmaxheight = 75; } // create a cache id $cachemod = md5($pdf); // does it exist in the cache, if so return it if (!$opts->nocache && file_exists($this->cachedir . '/' . $cachemod . '/json.txt')) { return json_decode(file_get_contents($this->cachedir . '/' . $cachemod . '/json.txt')); } try { // create our cache directory mkdir($this->cachedir . '/' . $cachemod, 0777, true); // filename $filename = $this->cachedir . '/' . $cachemod . '/' . basename($pdf); // download the file $bytes = file_put_contents($filename, file_get_contents($pdf)); // make sure we downloaded something if ($bytes === FALSE) { $json = array('error' => false, 'errormsg' => 'Could not download the PDF specified'); return $json; } // json to return $json = array('error' => false, 'pagecount' => 0, 'pdfurl' => $this->URL . $filename, 'thumbs' => array(), 'pages' => array(), 'geometry' => array('x' => 0, 'y' => 0)); // set up imagick instance $im = new Imagick(); // force resolution to screen $im->setResolution(72, 72); // read image $im->readImage($filename); // get image information $imageInfo = $im->identifyImage(); // ensure its a pdf! if (!$imageInfo || strpos(strtolower($imageInfo['format']), 'pdf') === FALSE) { $json = array('error' => false, 'errormsg' => 'The file specified is not a PDF!'); return $json; } // get geometry $geometry = $imageInfo['geometry']; $json['geometry'] = array('x' => $geometry['width'], 'y' => $geometry['height']); // resize ratio $ratio = 1; $thumbratio = 1; // landscape or portrait? if ($geometry['width'] > $geometry['height']) { if ($geometry['width'] > $opts->pagemaxwidth) { $ratio = $opts->pagemaxwidth / $geometry['width']; } } else { if ($geometry['height'] > $opts->pagemaxheight) { $ratio = $opts->pagemaxheight / $geometry['height']; } } // thumb ratio if ($geometry['width'] > $geometry['height']) { if ($geometry['width'] > $opts->thumbmaxwidth) { $thumbratio = $opts->thumbmaxwidth / $geometry['width']; } } else { if ($geometry['height'] > $opts->thumbmaxheight) { $thumbratio = $opts->thumbmaxheight / $geometry['height']; } } // get the number of pages $json['pagecount'] = $im->getNumberImages(); // loop over pagecount for ($i = 0; $i < $json['pagecount']; $i++) { // convert to jpg $im2 = new Imagick($filename . '[' . $i . ']'); // png for big image //$im2->setCompression(Imagick::COMPRESSION_PNG); $im2->setImageFormat('png'); $im2->setCompressionQuality(95.5); // main image max size $im2->resizeImage($geometry['width'] * $ratio, $geometry['height'] * $ratio, imagick::FILTER_UNDEFINED, 1); //write image on server $im2->writeImage($this->cachedir . '/' . $cachemod . '/page-' . $i . '.png'); // jpg for thumb $im2->setCompression(Imagick::COMPRESSION_JPEG); $im2->setCompressionQuality(95); $im2->setImageFormat('jpg'); // thumb resize $im2->resizeImage($geometry['width'] * $thumbratio, $geometry['height'] * $thumbratio, imagick::FILTER_UNDEFINED, 1); //write image on server $im2->writeImage($this->cachedir . '/' . $cachemod . '/thumb-' . $i . '.jpg'); // tidy up $im2->clear(); $im2->destroy(); // add to json $json['thumbs'][] = $this->CACHEURL . $cachemod . '/thumb-' . $i . '.jpg'; $json['pages'][] = $this->CACHEURL . $cachemod . '/page-' . $i . '.png'; } // tidy up $im->clear(); $im->destroy(); // put json into file file_put_contents($this->cachedir . '/' . $cachemod . '/json.txt', json_encode($json)); // return values return $json; } catch (exception $e) { return array('error' => true, 'errormsg' => $e->getMessage()); } }
/** * @param string $file * @param int $offsetX * @param int $offsetY * @param float $opacity * * @return static * @throws \ManaPHP\Image\Adapter\Exception */ public function watermark($file, $offsetX = 0, $offsetY = 0, $opacity = 1.0) { $watermark = new \Imagick($this->alias->resolve($file)); if ($watermark->getImageAlphaChannel() === \Imagick::ALPHACHANNEL_UNDEFINED) { $watermark->setImageOpacity($opacity); } if ($watermark->getNumberImages() !== 1) { throw new ImagickException('not support multiple iterations: `:file`', ['file' => $file]); } if (!$this->_image->compositeImage($watermark, \Imagick::COMPOSITE_OVER, $offsetX, $offsetY)) { throw new ImagickException('Imagick::compositeImage Failed'); } $watermark->clear(); $watermark->destroy(); return $this; }
/** * Image conversion abstraction. * * @param string $source * @param array $size * @return Imagick */ protected function _convert($source, $size) { extract($size); $im = new Imagick(); $js = 0; $hint = max($tw, $th) * $js; if ($hint > 0 && $hint < $sw && $hint < $sh) { if (pathinfo($source, PATHINFO_EXTENSION) === 'jpg') { $im->setOption('jpeg:size', sprintf('%dx%d', $hint, $hint)); } } $im->readImage($source); if ($im->getNumberImages() > 1) { $im->flattenImages(); } $colorspace = $im->getImageColorSpace(); if ($colorspace !== Imagick::COLORSPACE_RGB && $colorspace !== Imagick::COLORSPACE_SRGB) { $im->setImageColorSpace(Imagick::COLORSPACE_SRGB); } if ($im->getImageMatte()) { $im->setImageMatte(false); } if ($this->doesTrimming()) { $im->cropImage($sw, $sh, $sx, $sy); } if ($this->doesResampling()) { $im->resizeImage($tw, $th, Imagick::FILTER_LANCZOS, 0.9, true); } $im->stripImage(); $degrees = $this->getRotation(); if ($degrees) { $bgcolor = $this->getBgColor(); $bg = sprintf('rgb(%d,%d,%d)', $bgcolor[0], $bgcolor[1], $bgcolor[2]); $im->rotateImage(new ImagickPixel($bg), $degrees); } if ($this->isPng()) { $im->setFormat('PNG'); } else { $im->setFormat('JPEG'); if ($this->getQuality()) { $im->setCompressionQuality($this->getQuality()); } } return $im; }
public static function save_post($post_id) { if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE || !$_POST) { return; } if (current_user_can('edit_posts')) { $form_data = $_REQUEST; $pdf_file_id = isset($form_data['pdf_file_id']) ? $form_data['pdf_file_id'] : PdfLightViewer_Model::getPDFFileId($post_id); $pdf_file_path = get_attached_file($pdf_file_id); if ((isset($form_data['enable_pdf_import']) && $form_data['enable_pdf_import'] == 'on' || isset($form_data['enable_pdf_import']) && (isset($form_data['enable_pdf_import']['cmb-field-0']) || $form_data['enable_pdf_import']['cmb-field-0'])) && $pdf_file_id) { do_action(PDF_LIGHT_VIEWER_PLUGIN . ':before_import_scheduled', $pdf_file_path); $jpeg_compression_quality = isset($form_data['jpeg_compression_quality']) ? $form_data['jpeg_compression_quality'] : get_post_meta($post_id, 'jpeg_compression_quality', true); $jpeg_resolution = isset($form_data['jpeg_resolution']) ? $form_data['jpeg_resolution'] : get_post_meta($post_id, 'jpeg_resolution', true); $pdf_upload_dir = PdfLightViewer_Plugin::createUploadDirectory($post_id); // delete all files self::delete_pages_by_pdf_id($post_id, $pdf_upload_dir); if (class_exists('Imagick')) { $im = new Imagick(); $im->readImage($pdf_file_path); $pages_number = $im->getNumberImages(); foreach ($im as $_img) { $geometry = $_img->getImageGeometry(); $width = $geometry['width']; $height = $geometry['height']; break; } $im->destroy(); update_post_meta($post_id, '_pdf-light-viewer-import-status', static::STATUS_SCHEDULED); update_post_meta($post_id, '_pdf-light-viewer-import-progress', 0); update_post_meta($post_id, '_pdf-light-viewer-import-current-page', 1); update_post_meta($post_id, 'pdf-pages-number', $pages_number); update_post_meta($post_id, 'pdf-page-width', $width); update_post_meta($post_id, 'pdf-page-height', $height); PdfLightViewer_AdminController::showMessage(sprintf(__('PDF import scheduled.', PDF_LIGHT_VIEWER_PLUGIN), PdfLightViewer_Plugin::getSettingsUrl()), false); } else { PdfLightViewer_AdminController::showMessage(sprintf(__('Imagick not found, please check other requirements on <a href="%s">plugin settings page</a> for more information.', PDF_LIGHT_VIEWER_PLUGIN), PdfLightViewer_Plugin::getSettingsUrl()), true); } } } unset($_REQUEST['enable_pdf_import']); unset($_POST['enable_pdf_import']); }