예제 #1
0
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();
}
예제 #2
0
/**
 * @param $pdf
 * @param $id
 * @return string
 * @usage Generates thumbnail from PDF file. [ From v4.1.3 ]
 */
function wpdm_pdf_thumbnail($pdf, $id)
{
    $pdfurl = '';
    if (strpos($pdf, "://")) {
        $pdfurl = $pdf;
        $pdf = str_replace(home_url('/'), ABSPATH, $pdf);
    }
    if ($pdf == $pdfurl) {
        return;
    }
    if (file_exists($pdf)) {
        $source = $pdf;
    } else {
        $source = UPLOAD_DIR . $pdf;
    }
    $dest = WPDM_CACHE_DIR . "/pdfthumbs/{$id}.png";
    $durl = WPDM_BASE_URL . "cache/pdfthumbs/{$id}.png";
    $ext = explode(".", $source);
    $ext = end($ext);
    if ($ext != 'pdf') {
        return '';
    }
    if (file_exists($dest)) {
        return $durl;
    }
    $source = $source . '[0]';
    if (!class_exists('Imagick')) {
        return "Imagick is not installed properly";
    }
    try {
        $image = new imagick($source);
        $image->setResolution(800, 800);
        $image->setImageFormat("png");
        $image->writeImage($dest);
    } catch (Exception $e) {
        return '';
    }
    return $durl;
}
예제 #3
0
 /**
  * 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;
 }
예제 #4
0
ignore_user_abort(true);
set_time_limit(0);
// pixel cache max size
IMagick::setResourceLimit(imagick::RESOURCETYPE_MEMORY, 256);
// maximum amount of memory map to allocate for the pixel cache
IMagick::setResourceLimit(imagick::RESOURCETYPE_MAP, 256);
$mid = $_REQUEST['mid'];
mkdir("../upload/");
$fname = md5($file_name[1] . date() . rand(0, 100000)) . ".jpg";
while (file_exists("../../magazine/" . $mid . "/" . $fname)) {
    $fname = md5($file_name[1] . date() . rand(0, 100000)) . ".jpg";
}
move_uploaded_file($_FILES["file"]["tmp_name"], "../upload/" . $fname);
$img = new imagick();
$img->setResolution(500, 500);
$img->readimage("../upload/" . $fname);
$img->scaleImage(1000, 0);
$img->writeImage("../../magazine/" . $mid . "/" . $fname);
$img->scaleImage(200, 0);
$img->writeImage("../../magazine/" . $mid . "/small/" . $fname);
include "conn.php";
$sql = "SELECT `magazine`.`size` FROM `magazine` WHERE `magazine`.`id`=" . $mid . "";
$result = mysql_query($sql, $conn);
$row = mysql_fetch_array($result);
$sql = "INSERT INTO `pages` (`magazine`, `name`, `position`) VALUES (" . $mid . ", '" . $fname . "', '" . $row[0] . "');";
mysql_query($sql, $conn);
$sql = "UPDATE `magazine` SET size=size+1 WHERE `magazine`.`id`='" . $mid . "'";
mysql_query($sql, $conn);
echo mysql_insert_id($conn);
mysql_close($conn);
예제 #5
0
파일: pdf.php 프로젝트: jHolub/kalkulacka
<?php

phpinfo();
exit;
$pdf = './manual.pdf';
$fp_pdf = fopen($pdf, 'rb');
$img = new imagick();
// [0] can be used to set page number
$img->setResolution(300, 300);
$img->readImageFile($fp_pdf);
$img->setImageFormat("jpg");
$img->setImageCompression(imagick::COMPRESSION_JPEG);
$img->setImageCompressionQuality(90);
$img->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH);
$data = $img->getImageBlob();
예제 #6
0
 /**
  * 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;
     }
 }
예제 #7
0
 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;
 }
예제 #8
0
// pixel cache max size
IMagick::setResourceLimit(imagick::RESOURCETYPE_MEMORY, 256);
// maximum amount of memory map to allocate for the pixel cache
IMagick::setResourceLimit(imagick::RESOURCETYPE_MAP, 256);
include "conn.php";
mkdir("../upload/");
$series = $_REQUEST['series'];
$publisher = $_REQUEST['publisher'];
$file_name = explode(".", $_FILES['file']['name']);
$fname = md5($file_name[1] . date() . rand(0, 100000)) . "." . $file_name[1];
while (file_exists("../upload/" . $fname)) {
    $fname = md5($file_name[1] . date() . rand(0, 100000)) . "." . $file_name[1];
}
move_uploaded_file($_FILES["file"]["tmp_name"], "../upload/" . $fname);
$img = new imagick();
$img->setResolution(600, 600);
$img->readimage("../upload/" . $fname);
$pdfLength = $img->getNumberImages();
$sql = "INSERT INTO `magazine` (`size`, `series`, `issue`, `createtime`, `isnew`, `status`) VALUES (" . $pdfLength . "," . $series . ",0, '" . date("Y-m-d h:i:s") . "', 1, 0)";
mysql_query($sql, $conn);
$id = mysql_insert_id($conn);
if (!file_exists("../../magazine/")) {
    mkdir("../../magazine/");
}
mkdir("../../magazine/" . $id);
mkdir("../../magazine/" . $id . "/small");
$img->setImageFormat('jpeg');
for ($i = 0; $i < $pdfLength; $i++) {
    $img->setIteratorIndex($i);
    $img->scaleImage(1000, 0);
    $fname = md5($file_name[1] . date() . rand(0, 100000)) . ".jpg";
예제 #9
0
 /**
  * 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;
     }
 }
예제 #10
0
 /**
  * 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;
 }