function pdf2png($PDF,$Path){ if(!extension_loaded('imagick')){ echo 'no imagick'; return false; } if(!file_exists($PDF)){ echo 'no file'; return false; } $IM = new imagick(); echo 'image create'; // $IM->setResolution(794,1123); // echo 'image resolution'; $IM->setCompressionQuality(100); echo 'image quality'; $IM->readImage($PDF); echo 'pdf read'; foreach ($IM as $Key => $Var){ echo 'image convert'; $Var->setImageFormat('png'); $Filename = $Path.'/'.md5($Key.time()).'.png'; if($Var->writeImage($Filename) == true){ $Return[] = $Filename; } } return $Return; }
function pdftojpg($pdfFile, $jpgFile) { /* * imagemagick and php5-imagick required * * all options for imagick: * http://php.net/manual/fr/class.imagick.php * */ $pdf_file = $pdfFile; $save_to = $jpgFile; $img = new imagick(); //this must be called before reading the image, otherwise has no effect - "-density {$x_resolution}x{$y_resolution}" //this is important to give good quality output, otherwise text might be unclear $img->setResolution(200, 200); //read the pdf $img->readImage("{$pdf_file}[0]"); //reduce the dimensions - scaling will lead to black color in transparent regions $img->scaleImage(1920, 1080); //set new format $img->setCompressionQuality(80); $img->setImageFormat('jpg'); // -flatten option, this is necessary for images with transparency, it will produce white background for transparent regions $img = $img->flattenImages(); //save image file $img->writeImages($save_to, false); //clean $img->clear(); $img->destroy(); }
function pdf2png($PDF,$Path,$ImageName){ if(!extension_loaded('imagick')){ echo "<p>no imagick'</p>"; return false; } if(!file_exists($PDF)){ echo "<p>no file'</p>"; return false; } $IM = new imagick(); $IM->setOption('density','200'); $IM->setOption('antialias',''); $IM->setOption('sharpen','0x1.0'); //$IM->setResolution(794,1123); // echo 'image resolution'; $IM->setCompressionQuality(100); $IM->readImage($PDF); foreach ($IM as $Key => $Var){ $Var->paintTransparentImage($Var->getImageBackgroundColor(), 1, 10000); $Var->setImageFormat('png'); $Filename = $Path.'/'.$ImageName.'.png'; if($Var->writeImage($Filename) == true){ $Return[] = $Filename; } } return $Return; }
/** * Sets up an array of files to be deleted * * @param Model $model Model instance * @param string $field Name of field being modified * @param array $data array of data * @param array $options array of configuration settings for a field * @return boolean **/ protected function _prepareFilesForDeletion(Model $model, $field, $data, $options = array()) { if ($options['keepFilesOnDelete'] === true) { return array(); } if (!strlen($data[$model->alias][$field])) { return $this->__filesToRemove; } if (!empty($options['fields']['dir']) && isset($data[$model->alias][$options['fields']['dir']])) { $dir = $data[$model->alias][$options['fields']['dir']]; } else { if (in_array($options['pathMethod'], array('_getPathFlat', '_getPathPrimaryKey'))) { $model->id = $data[$model->alias][$model->primaryKey]; $dir = call_user_func(array($this, '_getPath'), $model, $field); } else { CakeLog::error(sprintf('Cannot get directory to %s.%s: %s pathMethod is not supported.', $model->alias, $field, $options['pathMethod'])); } } $filePathDir = $this->settings[$model->alias][$field]['path'] . (empty($dir) ? '' : $dir . DS); $filePath = $filePathDir . $data[$model->alias][$field]; $pathInfo = $this->_pathinfo($filePath); if (!isset($this->__filesToRemove[$model->alias])) { $this->__filesToRemove[$model->alias] = array(); } $this->__filesToRemove[$model->alias][] = $filePath; $this->__foldersToRemove[$model->alias][] = $dir; $createThumbnails = $options['thumbnails']; $hasThumbnails = !empty($options['thumbnailSizes']); if (!$createThumbnails || !$hasThumbnails) { return $this->__filesToRemove; } $directorySeparator = empty($dir) ? '' : DIRECTORY_SEPARATOR; $mimeType = $this->_getMimeType($filePath); $isMedia = $this->_isMedia($mimeType); $isImagickResize = $options['thumbnailMethod'] == 'imagick'; $thumbnailType = $options['thumbnailType']; if ($isImagickResize) { if ($isMedia) { $thumbnailType = $options['mediaThumbnailType']; } if (!$thumbnailType || !is_string($thumbnailType)) { try { $srcFile = $filePath; $image = new imagick(); if ($isMedia) { $image->setResolution(300, 300); $srcFile = $srcFile . '[0]'; } $image->readImage($srcFile); $thumbnailType = $image->getImageFormat(); } catch (Exception $e) { $thumbnailType = 'png'; } } } else { if (!$thumbnailType || !is_string($thumbnailType)) { $thumbnailType = $pathInfo['extension']; } if (!$thumbnailType) { $thumbnailType = 'png'; } } foreach ($options['thumbnailSizes'] as $size => $geometry) { $fileName = str_replace(array('{size}', '{geometry}', '{filename}', '{primaryKey}', '{time}', '{microtime}'), array($size, $geometry, $pathInfo['filename'], $model->id, time(), microtime()), $options['thumbnailName']); $thumbnailPath = $options['thumbnailPath']; $thumbnailPath = $this->_pathThumbnail($model, $field, compact('geometry', 'size', 'thumbnailPath')); $thumbnailFilePath = "{$thumbnailPath}{$dir}{$directorySeparator}{$fileName}.{$thumbnailType}"; $this->__filesToRemove[$model->alias][] = $thumbnailFilePath; } return $this->__filesToRemove; }
<?php define("JPEG_FILE", __DIR__ . "/imagick_test.jpg"); define("PNG_FILE", __DIR__ . "/imagick_test.png"); $im = new imagick('magick:rose'); $im->writeImage(JPEG_FILE); $im->clear(); // This is the problematic case, setImageFormat doesn't really // affect writeImageFile. // So in this case we want to write PNG but file should come out // as JPEG $fp = fopen(PNG_FILE, "w+"); $im->readImage(JPEG_FILE); $im->setImageFormat('png'); $im->writeImageFile($fp); $im->clear(); fclose($fp); // Output the format $identify = new Imagick(PNG_FILE); echo $identify->getImageFormat() . PHP_EOL; // Lets try again, setting the filename rather than format // This should cause PNG image to be written $fp = fopen(PNG_FILE, "w+"); $im->readImage(JPEG_FILE); $im->setImageFilename('png:'); $im->writeImageFile($fp); $im->clear(); fclose($fp); // If all goes according to plan, on second time we should get PNG $identify = new Imagick(PNG_FILE); echo $identify->getImageFormat() . PHP_EOL;
/** * Create thumnbnail and return it's URL on success * * @param string $path file path * @param $stat * @return false|string * @internal param string $mime file mime type * @author Dmitry (dio) Levashov */ protected function createTmb($path, $stat) { if (!$stat || !$this->canCreateTmb($path, $stat)) { return false; } $name = $this->tmbname($stat); $tmb = $this->tmbPath . DIRECTORY_SEPARATOR . $name; // copy image into tmbPath so some drivers does not store files on local fs if (($src = $this->fopenCE($path, 'rb')) == false) { return false; } if (($trg = fopen($tmb, 'wb')) == false) { $this->fcloseCE($src, $path); return false; } while (!feof($src)) { fwrite($trg, fread($src, 8192)); } $this->fcloseCE($src, $path); fclose($trg); $result = false; $tmbSize = $this->tmbSize; if ($this->imgLib === 'imagick') { try { $imagickTest = new imagick($tmb); $imagickTest->clear(); $imagickTest = true; } catch (Exception $e) { $imagickTest = false; } } if ($this->imgLib === 'imagick' && !$imagickTest || ($s = @getimagesize($tmb)) === false) { if ($this->imgLib === 'imagick') { try { $imagick = new imagick(); $imagick->setBackgroundColor(new ImagickPixel($this->options['tmbBgColor'])); $imagick->readImage($this->getExtentionByMime($stat['mime'], ':') . $tmb); $imagick->setImageFormat('png'); $imagick->writeImage($tmb); $imagick->clear(); if (($s = @getimagesize($tmb)) !== false) { $result = true; } } catch (Exception $e) { } } if (!$result) { unlink($tmb); return false; } $result = false; } /* If image smaller or equal thumbnail size - just fitting to thumbnail square */ if ($s[0] <= $tmbSize && $s[1] <= $tmbSize) { $result = $this->imgSquareFit($tmb, $tmbSize, $tmbSize, 'center', 'middle', $this->options['tmbBgColor'], 'png'); } else { if ($this->options['tmbCrop']) { $result = $tmb; /* Resize and crop if image bigger than thumbnail */ if (!($s[0] > $tmbSize && $s[1] <= $tmbSize || $s[0] <= $tmbSize && $s[1] > $tmbSize) || $s[0] > $tmbSize && $s[1] > $tmbSize) { $result = $this->imgResize($tmb, $tmbSize, $tmbSize, true, false, 'png'); } if ($result && ($s = @getimagesize($tmb)) != false) { $x = $s[0] > $tmbSize ? intval(($s[0] - $tmbSize) / 2) : 0; $y = $s[1] > $tmbSize ? intval(($s[1] - $tmbSize) / 2) : 0; $result = $this->imgCrop($result, $tmbSize, $tmbSize, $x, $y, 'png'); } else { $result = false; } } else { $result = $this->imgResize($tmb, $tmbSize, $tmbSize, true, true, 'png'); } if ($result) { $result = $this->imgSquareFit($result, $tmbSize, $tmbSize, 'center', 'middle', $this->options['tmbBgColor'], 'png'); } } if (!$result) { unlink($tmb); return false; } return $name; }
/** * Converts the PDF represented to one or more PNG files in the given * directory. The relative path of each generated PNG file is returned * in an array. * * If there is already a file at the destination with the name of one * of the parts, its not overwritten, and is instead assumed to be * an already generated version of the page. * * @param string $destination * A directory path to write the PNG files to. * * @return array * An array of zero or more strings, each describing a PNG file that was * created. */ public function convertToPNG($destination) { if (!is_dir($destination) or !is_writeable($destination)) { throw new Exception('"' . $destination . '" is not a writeable directory.'); } else { $pdf = new imagick(); $pdf->setResolution($this->x_resolution, $this->y_resolution); $pdf->readImage($this->PDFPath()); // Normalize the directory path by stripping off any possible trailing // slashes, and then tacking one on the end. $destination = rtrim($destination, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; $filename_parts = $this->parseFileName(basename($this->PDFPath())); // An array to keep track of the names of all the png // images we generate from pages of the PDF. $generated_images = array(); foreach ($pdf as $index => $a_page) { $file_name = $destination . $filename_parts['base'] . '-' . ($index + 1) . '.png'; // If there is already a file with this name on the filesystem, // don't overwrite it. Instead, assume its identical to what // we'd have generated and return the name anyway. if (!is_file($file_name)) { $a_page->setImageFormat('png'); $a_page->setFilename($file_name); $a_page->writeImage($file_name); } $generated_images[] = $file_name; } return $generated_images; } }
function _prepareFilesForDeletion(&$model, $field, $data, $options) { if (!strlen($data[$model->alias][$field])) { return $this->__filesToRemove; } $dir = $data[$model->alias][$options['fields']['dir']]; $filePathDir = $this->settings[$model->alias][$field]['path'] . $dir . DS; $filePath = $filePathDir . $data[$model->alias][$field]; $pathInfo = $this->_pathinfo($filePath); $this->__filesToRemove[$model->alias] = array(); $this->__filesToRemove[$model->alias][] = $filePath; $createThumbnails = $options['thumbnails']; $hasThumbnails = !empty($options['thumbnailSizes']); if (!$createThumbnails || !$hasThumbnails) { return $this->__filesToRemove; } $DS = DIRECTORY_SEPARATOR; $mimeType = $this->_getMimeType($filePath); $isMedia = $this->_isMedia($model, $mimeType); $isImagickResize = $options['thumbnailMethod'] == 'imagick'; $thumbnailType = $options['thumbnailType']; if ($isImagickResize) { if ($isMedia) { $thumbnailType = $options['mediaThumbnailType']; } if (!$thumbnailType || !is_string($thumbnailType)) { try { $srcFile = $filePath; $image = new imagick(); if ($isMedia) { $image->setResolution(300, 300); $srcFile = $srcFile . '[0]'; } $image->readImage($srcFile); $thumbnailType = $image->getImageFormat(); } catch (Exception $e) { $thumbnailType = 'png'; } } } else { if (!$thumbnailType || !is_string($thumbnailType)) { $thumbnailType = $pathInfo['extension']; } if (!$thumbnailType) { $thumbnailType = 'png'; } } foreach ($options['thumbnailSizes'] as $size => $geometry) { $fileName = str_replace(array('{size}', '{filename}'), array($size, $pathInfo['filename']), $options['thumbnailName']); $thumbnailPath = $options['thumbnailPath']; $thumbnailPath = $this->_pathThumbnail($model, $field, compact('geometry', 'size', 'thumbnailPath')); $thumbnailFilePath = "{$thumbnailPath}{$dir}{$DS}{$fileName}.{$thumbnailType}"; $this->__filesToRemove[$model->alias][] = $thumbnailFilePath; } return $this->__filesToRemove; }
private function resizeCropImg($pFolder, $pImg, $pW, $pH) { $im = new imagick(); $im->readImage($pFolder . $pImg); $image = new stdClass(); $image->dimensions = $im->getImageGeometry(); $image->w = $image->dimensions['width']; $image->h = $image->dimensions['height']; $image->ratio = $image->w / $image->h; if ($image->w / $pW < $image->h / $pH) { $h = ceil($pH * $image->w / $pW); $y = ($image->h - $pH * $image->w / $pW) / 2; $im->cropImage($image->w, $h, 0, $y); } else { $w = ceil($pW * $image->h / $pH); $x = ($image->w - $pW * $image->h / $pH) / 2; $im->cropImage($w, $image->h, $x, 0); } $im->ThumbnailImage($pW, $pH, true); if ($img->type === "PNG") { $im->setImageCompressionQuality(55); $im->setImageFormat('png'); } elseif ($img->type === "JPG" || $img->type === "JPEG") { $im->setCompressionQuality(100); $im->setImageFormat("jpg"); } $im->writeImage($this->ad->url->folder . '/assets/' . $pImg); $im->destroy(); }
/** * Create thumnbnail and return it's URL on success * * @param string $path file path * @param $stat * @return false|string * @internal param string $mime file mime type * @author Dmitry (dio) Levashov */ protected function createTmb($path, $stat) { if (!$stat || !$this->canCreateTmb($path, $stat)) { return false; } $name = $this->tmbname($stat); $tmb = $this->tmbPath . DIRECTORY_SEPARATOR . $name; $maxlength = -1; $imgConverter = null; // check imgConverter $mime = strtolower($stat['mime']); list($type) = explode('/', $mime); if (isset($this->imgConverter[$mime])) { $imgConverter = $this->imgConverter[$mime]['func']; if (!empty($this->imgConverter[$mime]['maxlen'])) { $maxlength = intval($this->imgConverter[$mime]['maxlen']); } } else { if (isset($this->imgConverter[$type])) { $imgConverter = $this->imgConverter[$type]['func']; if (!empty($this->imgConverter[$type]['maxlen'])) { $maxlength = intval($this->imgConverter[$type]['maxlen']); } } } if ($imgConverter && !is_callable($imgConverter)) { return false; } // copy image into tmbPath so some drivers does not store files on local fs if (($src = $this->fopenCE($path, 'rb')) == false) { return false; } if (($trg = fopen($tmb, 'wb')) == false) { $this->fcloseCE($src, $path); return false; } stream_copy_to_stream($src, $trg, $maxlength); $this->fcloseCE($src, $path); fclose($trg); // call imgConverter if ($imgConverter) { if (!call_user_func_array($imgConverter, array($tmb, $stat, $this))) { file_exists($tmb) && unlink($tmb); return false; } } $result = false; $tmbSize = $this->tmbSize; if ($this->imgLib === 'imagick') { try { $imagickTest = new imagick($tmb); $imagickTest->clear(); $imagickTest = true; } catch (Exception $e) { $imagickTest = false; } } if ($this->imgLib === 'imagick' && !$imagickTest || ($s = getimagesize($tmb)) === false) { if ($this->imgLib === 'imagick') { $bgcolor = $this->options['tmbBgColor']; if ($bgcolor === 'transparent') { $bgcolor = 'rgba(255, 255, 255, 0.0)'; } try { $imagick = new imagick(); $imagick->setBackgroundColor(new ImagickPixel($bgcolor)); $imagick->readImage($this->getExtentionByMime($stat['mime'], ':') . $tmb); $imagick->setImageFormat('png'); $imagick->writeImage($tmb); $imagick->clear(); if (($s = getimagesize($tmb)) !== false) { $result = true; } } catch (Exception $e) { } } if (!$result) { file_exists($tmb) && unlink($tmb); return false; } $result = false; } /* If image smaller or equal thumbnail size - just fitting to thumbnail square */ if ($s[0] <= $tmbSize && $s[1] <= $tmbSize) { $result = $this->imgSquareFit($tmb, $tmbSize, $tmbSize, 'center', 'middle', $this->options['tmbBgColor'], 'png'); } else { if ($this->options['tmbCrop']) { $result = $tmb; /* Resize and crop if image bigger than thumbnail */ if (!($s[0] > $tmbSize && $s[1] <= $tmbSize || $s[0] <= $tmbSize && $s[1] > $tmbSize) || $s[0] > $tmbSize && $s[1] > $tmbSize) { $result = $this->imgResize($tmb, $tmbSize, $tmbSize, true, false, 'png'); } if ($result && ($s = getimagesize($tmb)) != false) { $x = $s[0] > $tmbSize ? intval(($s[0] - $tmbSize) / 2) : 0; $y = $s[1] > $tmbSize ? intval(($s[1] - $tmbSize) / 2) : 0; $result = $this->imgCrop($result, $tmbSize, $tmbSize, $x, $y, 'png'); } else { $result = false; } } else { $result = $this->imgResize($tmb, $tmbSize, $tmbSize, true, true, 'png'); } if ($result) { if ($s = getimagesize($tmb)) { if ($s[0] !== $tmbSize || $s[1] !== $tmbSize) { $result = $this->imgSquareFit($result, $tmbSize, $tmbSize, 'center', 'middle', $this->options['tmbBgColor'], 'png'); } } } } if (!$result) { unlink($tmb); return false; } return $name; }
/** * Convert to output format. This method convert from pdf to specified format with optimizing * @throw Exception * @access public * @param string $outputPath - path to file. May content only path or path with filename * @param int/string[=ALL] $page - number of document page wich will be converted into image. If specified 'ALL' - will be converted all pages. * @param string $format - output format (see self::getFormats()) * @param array $resolution - array with x&y resolution DPI * @param int $depth - bit depth image * @return string/bool[false] - return image path of last converted page */ public function convert($outputPath = '', $page = 'ALL', $format = 'png', $resolution = array('x' => 300, 'y' => 300), $depth = 8) { if (!Imagick::queryFormats(strtoupper($format))) { throw new Exception('Unsupported format'); } $startTime = microtime(true); $im = new imagick(); $im->setResolution($resolution['x'], $resolution['y']); $format = strtolower($format); $im->setFormat($format); if ($outputPath) { if (is_dir($outputPath)) { $outputPath = $outputPath . pathinfo($this->filePathWithoutType, PATHINFO_FILENAME); } $outputFileName = $outputPath; } else { $outputFileName = $this->filePathWithoutType; } if ($page === 'ALL') { $im->readImage($this->filePathWithoutType . '.pdf'); $im->setImageFormat($format); $im->setImageAlphaChannel(11); // it's a new constant imagick::ALPHACHANNEL_REMOVE $im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN); $im->setOption($format . ':bit-depth', $depth); $im->writeImages($outputFileName . "." . $format, false); $logString = '[POINT] File "' . $this->filePathWithoutType . '.pdf" converted to "' . $format . '" with ' . $im->getNumberImages() . ' pages (ex: ' . (microtime(true) - $startTime) . 's)'; $this->setLog($logString); //Optimizing if ($format == 'png' && $this->optipngChecking()) { $startTime = microtime(true); for ($page = $i = 0; $i < $im->getNumberImages(); $i++) { $this->execute('optipng -o=5', $outputFileName . "-" . (int) $i . "." . $format); } $logString = '[POINT] Files "' . $outputFileName . '-x.' . $format . '" optimized (ex: ' . (microtime(true) - $startTime) . 's)'; $this->setLog($logString); } } else { $im->readImage($this->filePathWithoutType . '.pdf[' . (int) $page . ']'); $im->setImageFormat($format); $im->setImageAlphaChannel(11); // it's a new constant imagick::ALPHACHANNEL_REMOVE $im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN); $im->setOption($format . ':color-type', 2); $im->setOption($format . ':bit-depth', $depth); $im->writeImage($outputFileName . "-" . (int) $page . "." . $format); $logString = '[POINT] File "' . $outputFileName . '.pdf" converted to "' . $format . '" one page (ex: ' . (microtime(true) - $startTime) . 's)'; $this->setLog($logString); //Optimizing if ($format == 'png' && $this->optipngChecking()) { $startTime = microtime(true); $this->execute('optipng -o=5', $outputFileName . "-" . (int) $page . "." . $format); $logString = '[POINT] File "' . $outputFileName . "-" . (int) $page . "." . $format . '" optimized (ex: ' . (microtime(true) - $startTime) . 's)'; $this->setLog($logString); } } if (file_exists($outputFileName . "-" . (int) $page . "." . $format)) { return $outputFileName . "-" . (int) $page . "." . $format; } else { return false; } }
/** * class_make_file::create_img_frompdf() * * @param mixed $pdf_org * @param mixed $pfadhier * @return */ private function create_img_frompdf($pdf_org, $pfadhier) { setlocale(LC_ALL, "de_DE"); //Klasse INI $im = new imagick(); //Auflösung $im->setResolution(60, 60); //Anzahl der Seiten des PDFs $pages = $this->getNumPagesInPDF($pfadhier . $pdf_org); //Dann alle Seiten durchlaufen und Bilder erzeugen for ($i = 0; $i < $pages; $i++) { //Maximal 100 Seiten if ($i > 100) { continue; } //Seitenzahl festlegen $pdf = $pfadhier . $pdf_org . "[" . $i . "]"; //auslesen if (file_exists($pfadhier . $pdf_org)) { try { $im->readImage($pdf); } catch (Exception $e) { echo 'Exception abgefangen: ', $e->getMessage(), "\n"; } if (empty($e)) { //die ("NIX"); $im->setImageColorspace(255); $im->setCompression(Imagick::COMPRESSION_JPEG); $im->setCompressionQuality(60); $im->setImageFormat('jpg'); $im->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH); //Damti testweise ausgeben #header( "Content-Type: image/png" ); #echo $im; #exit(); $pdf_img = str_replace(".pdf", "", $pdf_org); $pdf_img = str_replace("/files/pdf/", "", $pdf_img); $im->setImageFileName($pfadhier . "files/images/thumbs/" . $pdf_img . "_" . $i . ".jpg"); //Pfade saven echo $image_files[] = $pfadhier . "files/images/thumbs/" . $pdf_img . "_" . $i . ".jpg"; //Speichern $im->writeImage(); ini_set(Display_errors, "1"); } //Noch verkleinern... image_magick macht die Bilder zu groß /** $image = new SimpleImage(); $image->load($pfadhier."files/images/thumbs/".$pdf_img."_".$i.".jpg"); $image->resizeToHeight(300); $image->save($pfadhier."files/images/thumbs/".$pdf_img."_".$i."x.jpg"); unlink($pfadhier."files/images/thumbs/".$pdf_img."_".$i.".jpg"); echo ($pfadhier."files/images/thumbs/".$pdf_img."_".$i."x.jpg"); */ } } return $image_files; }