function convert_to_IMG($attachment, $options) { $path = get_path($attachment); $dir = get_dir($attachment); $basename = get_basename($attachment); $converted_images = array(); $max_width = $options['max_width'] ? (int) $options['max_width'] : 0; $max_height = $options['max_height'] ? (int) $options['max_height'] : 0; $img_extension = $options['img_extension'] ? $options['img_extension'] : 'jpg'; $pages_to_convert = $options["pages_to_convert"] ? (int) $options["pages_to_convert"] : 0; if ($pages_to_convert > 5) { $pages_to_convert = 5; } $pages_to_convert = $pages_to_convert - 1; $quality = $options['quality'] ? (int) $options['quality'] : 80; if ($quality > 100) { $quality = 100; } try { $imagick = new Imagick(); $imagick->clear(); $imagick->destroy(); if ($options) { $imagick->setResolution(150, 150); $imagick->readimage($path); $imagick->setCompressionQuality($quality); } else { $imagick->setResolution(72, 72); $imagick->readimage($path); } foreach ($imagick as $c => $_page) { if ($pages_to_convert == -1 || $c <= $pages_to_convert) { $_page->setImageBackgroundColor('white'); $_page->setImageFormat($img_extension); if ($max_width && $max_height) { $_page->adaptiveResizeImage($max_width, $max_height, true); } $blankPage = new \Imagick(); $blankPage->newPseudoImage($_page->getImageWidth(), $_page->getImageHeight(), "canvas:white"); $blankPage->compositeImage($_page, \Imagick::COMPOSITE_OVER, 0, 0); if ($blankPage->writeImage($dir . "/" . $basename . '-' . $c . '.' . $img_extension)) { array_push($converted_images, $dir . "/" . $basename . '-' . $c . '.' . $img_extension); } $blankPage->clear(); $blankPage->destroy(); } } } catch (ImagickException $e) { $converted_images = false; } catch (Exception $e) { $converted_images = false; } return $converted_images; }
/** * @param $width * @param $height * @return self */ public function resize($width, $height) { $this->preModify(); // this is the check for vector formats because they need to have a resolution set // this does only work if "resize" is the first step in the image-pipeline if ($this->isVectorGraphic()) { // the resolution has to be set before loading the image, that's why we have to destroy the instance and load it again $res = $this->resource->getImageResolution(); $x_ratio = $res['x'] / $this->getWidth(); $y_ratio = $res['y'] / $this->getHeight(); $this->resource->removeImage(); $newRes = ["x" => $width * $x_ratio, "y" => $height * $y_ratio]; // only use the calculated resolution if we need a higher one that the one we got from the metadata (getImageResolution) // this is because sometimes the quality is much better when using the "native" resulution from the metadata if ($newRes["x"] > $res["x"] && $newRes["y"] > $res["y"]) { $this->resource->setResolution($newRes["x"], $newRes["y"]); } else { $this->resource->setResolution($res["x"], $res["y"]); } $this->resource->readImage($this->imagePath); $this->setColorspaceToRGB(); } $width = (int) $width; $height = (int) $height; $this->resource->resizeimage($width, $height, \Imagick::FILTER_UNDEFINED, 1, false); $this->setWidth($width); $this->setHeight($height); $this->postModify(); return $this; }
function getPage($page) { $format = $this->parameters['format_image']; switch ($format) { case "imagick": case "png": $extension = "png"; $content_type = "image/x-png"; break; case "jpeg": $extension = "jpg"; $content_type = "image/jpeg"; break; } $len = strlen($this->getPageCount()); if (!file_exists($this->doc->driver->get_cached_filename($this->doc->id) . "-" . str_pad($page, $len, "0", STR_PAD_LEFT) . "." . $extension)) { $resolution = $this->parameters['resolution_image']; if ($format == "imagick") { exec("pdftoppm -f {$page} -l {$page} -r " . $resolution . " " . $this->doc->driver->get_cached_filename($this->doc->id) . " " . $this->doc->driver->get_cached_filename("page_" . $this->doc->id)); $imagick = new Imagick(); $imagick->setResolution($resolution, $resolution); $imagick->readImage($this->doc->driver->get_cached_filename("page_" . $this->doc->id) . "-" . str_pad($page, $len, "0", STR_PAD_LEFT) . ".ppm"); $imagick->writeImage($this->doc->driver->get_cached_filename("page_" . $this->doc->id) . "-" . str_pad($page, $len, "0", STR_PAD_LEFT) . ".png"); unlink($this->doc->driver->get_cached_filename("page_" . $this->doc->id) . "-" . str_pad($page, $len, "0", STR_PAD_LEFT) . ".ppm"); } else { exec("pdftoppm -f {$page} -l {$page} -r " . $resolution . " -" . $format . " " . $this->doc->driver->get_cached_filename($this->doc->id) . " " . $this->doc->driver->get_cached_filename("page_" . $this->doc->id)); } } if (file_exists($this->doc->driver->get_cached_filename("page_" . $this->doc->id) . "-" . str_pad($page, $len, "0", STR_PAD_LEFT) . "." . $extension)) { header("Content-Type: " . $content_type); print file_get_contents($this->doc->driver->get_cached_filename("page_" . $this->doc->id) . "-" . str_pad($page, $len, "0", STR_PAD_LEFT) . "." . $extension); } }
/** * @param Thumbnail $thumbnail * @return void * @throws Exception\NoThumbnailAvailableException */ public function refresh(Thumbnail $thumbnail) { try { $filenameWithoutExtension = pathinfo($thumbnail->getOriginalAsset()->getResource()->getFilename(), PATHINFO_FILENAME); $temporaryLocalCopyFilename = $thumbnail->getOriginalAsset()->getResource()->createTemporaryLocalCopy(); $documentFile = sprintf(in_array($thumbnail->getOriginalAsset()->getResource()->getFileExtension(), $this->getOption('paginableDocuments')) ? '%s[0]' : '%s', $temporaryLocalCopyFilename); $width = $thumbnail->getConfigurationValue('width') ?: $thumbnail->getConfigurationValue('maximumWidth'); $height = $thumbnail->getConfigurationValue('height') ?: $thumbnail->getConfigurationValue('maximumHeight'); $im = new \Imagick(); $im->setResolution($this->getOption('resolution'), $this->getOption('resolution')); $im->readImage($documentFile); $im->setImageFormat('png'); $im->setImageBackgroundColor('white'); $im->setImageCompose(\Imagick::COMPOSITE_OVER); $im->setImageAlphaChannel(\Imagick::ALPHACHANNEL_RESET); $im->thumbnailImage($width, $height, true); $im->flattenImages(); // Replace flattenImages in imagick 3.3.0 // @see https://pecl.php.net/package/imagick/3.3.0RC2 // $im->mergeImageLayers(\Imagick::LAYERMETHOD_MERGE); $resource = $this->resourceManager->importResourceFromContent($im->getImageBlob(), $filenameWithoutExtension . '.png'); $im->destroy(); $thumbnail->setResource($resource); $thumbnail->setWidth($width); $thumbnail->setHeight($height); } catch (\Exception $exception) { $filename = $thumbnail->getOriginalAsset()->getResource()->getFilename(); $sha1 = $thumbnail->getOriginalAsset()->getResource()->getSha1(); $message = sprintf('Unable to generate thumbnail for the given document (filename: %s, SHA1: %s)', $filename, $sha1); throw new Exception\NoThumbnailAvailableException($message, 1433109652, $exception); } }
public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) { $mimetype = $fileview->getMimeType($path); $path = \OC_Helper::mimetypeIcon($mimetype); $path = \OC::$SERVERROOT . substr($path, strlen(\OC::$WEBROOT)); $svgPath = substr_replace($path, 'svg', -3); if (extension_loaded('imagick') && file_exists($svgPath) && count(@\Imagick::queryFormats("SVG")) === 1) { // http://www.php.net/manual/de/imagick.setresolution.php#85284 $svg = new \Imagick(); $svg->readImage($svgPath); $res = $svg->getImageResolution(); $x_ratio = $res['x'] / $svg->getImageWidth(); $y_ratio = $res['y'] / $svg->getImageHeight(); $svg->removeImage(); $svg->setResolution($maxX * $x_ratio, $maxY * $y_ratio); $svg->setBackgroundColor(new \ImagickPixel('transparent')); $svg->readImage($svgPath); $svg->setImageFormat('png32'); $image = new \OC_Image(); $image->loadFromData($svg); } else { $image = new \OC_Image($path); } return $image; }
public function getPng($resolutionX = 100, $resolutionY = 100) { $img = new \Imagick(); $img->setResolution($resolutionX, $resolutionY); $img->readImageBlob($this->get()); $img->setImageFormat('png'); return $img->getImageBlob(); }
private function convert($item, $page) { $im = new Imagick($item->internalPath() . '[' . ($page - 1) . ']'); $im->setResolution(1600, 1600); $im->setImageFormat('jpg'); header('Content-Type: image/jpeg'); echo $im; die; }
/** * Write a rendered PDF to the cache. * * @param $filePath * @param $cacheLocation */ protected function processFileToImageCache($filePath, $cacheLocation) { if (!is_dir($cacheLocation)) { mkdir($cacheLocation); } $imagick = new \Imagick(); $imagick->setResolution(150, 150); $imagick->readImage($filePath); $imagick->writeImages($cacheLocation . '/rendered.jpg', true); }
/** * @param $width * @param $height * @return Pimcore_Image_Adapter */ public function resize($width, $height) { // this is the check for vector formats because they need to have a resolution set // this does only work if "resize" is the first step in the image-pipeline if ($this->isVectorGraphic()) { // the resolution has to be set before loading the image, that's why we have to destroy the instance and load it again $res = $this->resource->getImageResolution(); $x_ratio = $res['x'] / $this->resource->getImageWidth(); $y_ratio = $res['y'] / $this->resource->getImageHeight(); $this->resource->removeImage(); $this->resource->setResolution($width * $x_ratio, $height * $y_ratio); $this->resource->readImage($this->imagePath); } else { $this->resource->resizeimage($width, $height, Imagick::FILTER_UNDEFINED, 1, false); } $this->setWidth($width); $this->setHeight($height); $this->reinitializeImage(); return $this; }
/** * Sets up Imagick for PDF processing. * Increases rendering DPI and only loads first page. * * @since 4.7.0 * @access protected * * @return string|WP_Error File to load or WP_Error on failure. */ protected function pdf_setup() { try { // By default, PDFs are rendered in a very low resolution. // We want the thumbnail to be readable, so increase the rendering DPI. $this->image->setResolution(128, 128); // Only load the first page. return $this->file . '[0]'; } catch (Exception $e) { return new WP_Error('pdf_setup_failed', $e->getMessage(), $this->file); } }
public function create($width, $height, $format = 'png') { // Destroy first? $this->destroy(); // Create $resource = new Imagick(); $resource->setResolution($width, $height); $resource->newImage(100, 100, new ImagickPixel('none'), $format); $resource->setImageFormat($format); // Save resource $this->_resource = $resource; return $this; }
function imgetimagesize($imagefile) { if (class_exists('Imagick')) { $im = new Imagick(); $im->setResolution( 300, 300 ); $im->readImage($imagefile); $width = $im->getImageWidth(); $height = $im->getImageHeight(); $type = $im->getImageType(); $attr = "width=\"$width\" height=\"$height\""; } else { list($width, $height, $type, $attr) = getimagesize($imagefile); } return array($width, $height, $type, $attr); }
/** * Loads image from $this->file into new Imagick Object. * * @since 3.5.0 * @access protected * * @return true|WP_Error True if loaded; WP_Error on failure. */ public function load() { if ($this->image instanceof Imagick) { return true; } if (!is_file($this->file) && !preg_match('|^https?://|', $this->file)) { return new WP_Error('error_loading_image', __('File doesn’t exist?'), $this->file); } /* * Even though Imagick uses less PHP memory than GD, set higher limit * for users that have low PHP.ini limits. */ wp_raise_memory_limit('image'); try { $this->image = new Imagick(); $file_parts = pathinfo($this->file); $filename = $this->file; // By default, PDFs are rendered in a very low resolution. // We want the thumbnail to be readable, so increase the rendering dpi. if ('pdf' == strtolower($file_parts['extension'])) { $this->image->setResolution(128, 128); // Only load the first page. $filename .= '[0]'; } // Reading image after Imagick instantiation because `setResolution` // only applies correctly before the image is read. $this->image->readImage($filename); if (!$this->image->valid()) { return new WP_Error('invalid_image', __('File is not an image.'), $this->file); } // Select the first frame to handle animated images properly if (is_callable(array($this->image, 'setIteratorIndex'))) { $this->image->setIteratorIndex(0); } $this->mime_type = $this->get_mime_type($this->image->getImageFormat()); } catch (Exception $e) { return new WP_Error('invalid_image', $e->getMessage(), $this->file); } $updated_size = $this->update_size(); if (is_wp_error($updated_size)) { return $updated_size; } return $this->set_quality(); }
/** * {@inheritdoc} */ public function createVariation(ImageFormat $output_format, $quality, ImageDimensions $dimensions = null, ImageCropDimensions $crop_dimensions = null) { $src = $this->getTempFile($this->data); $img = new \Imagick(); $img->setResolution($this->resolution, $this->resolution); $img->readImage($src); $img->setIteratorIndex(0); // Flatten images here helps the encoder to get rid of the black background // that appears on encoded image files. $img = $img->flattenImages(); $img->setImageFormat((string) $output_format->value()); $img->setImageCompressionQuality($quality); if (null !== $crop_dimensions) { $img->cropImage($crop_dimensions->getWidth(), $crop_dimensions->getHeight(), $crop_dimensions->getX(), $crop_dimensions->getY()); } if (null !== $dimensions) { $img->resizeImage($dimensions->getWidth() ?: 0, $dimensions->getHeight() ?: 0, $this->filter, 1, false); } return $img->getImageBlob(); }
/** * @param $width * @param $height * @return Pimcore_Image_Adapter */ public function resize($width, $height) { // this is the check for vector formats because they need to have a resolution set // this does only work if "resize" is the first step in the image-pipeline $type = $this->resource->getimageformat(); $vectorTypes = array("EPT", "EPDF", "EPI", "EPS", "EPS2", "EPS3", "EPSF", "EPSI", "EPT", "PDF", "PFA", "PFB", "PFM", "PS", "PS2", "PS3", "PSB", "SVG", "SVGZ"); if (in_array($type, $vectorTypes)) { // the resolution has to be set before loading the image, that's why we have to destroy the instance and load it again $res = $this->resource->getImageResolution(); $x_ratio = $res['x'] / $this->resource->getImageWidth(); $y_ratio = $res['y'] / $this->resource->getImageHeight(); $this->resource->removeImage(); $this->resource->setResolution($width * $x_ratio, $height * $y_ratio); $this->resource->readImage($this->imagePath); } else { $this->resource->resizeimage($width, $height, Imagick::FILTER_UNDEFINED, 1, false); } $this->setWidth($width); $this->setHeight($height); $this->reinitializeImage(); return $this; }
/** * Get the svg as an image * * @return \Imagecow\Image */ public function get($width = 0, $height = 0) { $imageWidth = $this->image->getImageWidth(); $imageHeight = $this->image->getImageHeight(); if ($width !== 0 && ($height === 0 || $imageWidth / $width > $imageHeight / $height)) { $height = ceil($width / $imageWidth * $imageHeight); } elseif ($height !== 0) { $width = ceil($height / $imageHeight * $imageWidth); } else { $width = $imageWidth; $height = $imageHeight; } $image = new \Imagick(); $image->setBackgroundColor(new \ImagickPixel('transparent')); $image->setResolution($width, $height); $blob = $this->image->getImageBlob(); $blob = preg_replace('/<svg([^>]*) width="([^"]*)"/si', '<svg$1 width="' . $width . 'px"', $blob); $blob = preg_replace('/<svg([^>]*) height="([^"]*)"/si', '<svg$1 height="' . $height . 'px"', $blob); $image->readImageBlob($blob); $image->setImageFormat("png"); return new \Imagecow\Image(new \Imagecow\Libs\Imagick($image)); }
/** * Internal * * Applies options before save or output * * @param \Imagick $image * @param array $options */ private function applyImageOptions(\Imagick $image, array $options) { if (isset($options['quality'])) { $image->setImageCompressionQuality($options['quality']); } if (isset($options['resolution-units']) && isset($options['resolution-x']) && isset($options['resolution-y'])) { if ($options['resolution-units'] == ImageInterface::RESOLUTION_PIXELSPERCENTIMETER) { $image->setImageUnits(\Imagick::RESOLUTION_PIXELSPERCENTIMETER); } elseif ($options['resolution-units'] == ImageInterface::RESOLUTION_PIXELSPERINCH) { $image->setImageUnits(\Imagick::RESOLUTION_PIXELSPERINCH); } else { throw new RuntimeException('Unsupported image unit format'); } $image->setResolution($options['resolution-x'], $options['resolution-y']); } }
public function makePreview($pdf_path, $preview_path) { $im = new Imagick(); $im->setResolution(300, 300); $im->readimage($pdf_path . '[0]'); $im->setImageFormat('jpeg'); $im->resizeimage(538, 360, Imagick::FILTER_LANCZOS, 1); $im->writeImage($preview_path); $im->clear(); $im->destroy(); }
/** * Return raw image data. * * @param string $pathToImage * * @return \Imagick */ public function getImageData($pathToImage) { $imagick = new \Imagick(); $imagick->setResolution($this->resolution, $this->resolution); $imagick->readImage(sprintf('%s[%s]', $this->pdfFile, $this->page - 1)); $imagick->mergeImageLayers(\Imagick::LAYERMETHOD_FLATTEN); $imagick->setFormat($this->determineOutputFormat($pathToImage)); return $imagick; }
if (isset($_GET['debug'])) { echo '<pre> "ACTION->key[payload description](default)" POST->image[base64 encoded pdf](local out.pdf test) GET->format[png jpg eps etc.](png) GET->show[](prints image header for browser display if present) GET->debug[](prints debug info if present) GET->dpi[a number](300) </pre>'; } $image = new Imagick(); $dpi = 300; if (isset($_GET['dpi'])) { $dpi = (double) $_GET['dpi']; } $image->setResolution($dpi, $dpi); if (isset($_POST['image'])) { $decoded = base64_decode($_POST['image']); $image->readimageblob($decoded); } else { if (isset($pdftopng)) { //todo include pdftopng inline rather than utilizing as a webservice// $image->readImage($pdftopng); } else { $myurl = 'out.pdf'; $image->readImage($myurl); } } $format = "png"; if (isset($_GET['format'])) { $format = (string) $_GET['format'];
function pdf_image($load_number) { $imagick = new Imagick(); $imagick->setResolution(200, 200); $imagick->readImage(CONT_FILE_PATH . $load_number . '.pdf'); $imagick->extentImage(1700, 2200, 0, 0); $imagick->setImageFormat('jpeg'); $imagick->writeImage(CONT_FILE_PATH . $load_number . '.jpg'); }
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()); } }
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'; }
private function generate_adobe_thumb($working_dir, $input_filename, $output_filename) { $pos = strrpos($input_filename, "."); $input_extension = substr($input_filename, $pos + 1); $input_path = $working_dir . "/{$input_filename}"; $output_extension = "png"; $image = new Imagick($input_path); $image->setResolution(300, 300); $image->setImageFormat($output_extension); if ($input_extension == "psd") { $image->setIteratorIndex(0); } $success = $image->writeImage($working_dir . "/{$output_filename}"); return $success; }
//$sizes[] = array( '/project' . $assets_path . '/blackberry/splash-768x1280.png', 768, 1280, 72 ); } $portrait = in_array('portrait', $_POST['orientations']); $landscape = in_array('landscape', $_POST['orientations']); foreach ($sizes as $size) { if (!$portrait && $size[SPLASH_WIDTH] < $size[SPLASH_HEIGHT] || !$landscape && $size[SPLASH_WIDTH] > $size[SPLASH_HEIGHT]) { continue; } $file = $tmp_path . $size[ICON_PATH]; $dir = dirname($file); if (is_dir($dir) == false) { mkdir($dir, 0777, true); } $ext = substr($size[SPLASH_PATH], strrpos($size[SPLASH_PATH], '.') + 1); $image = new Imagick(); $image->setResolution($size[SPLASH_DPI], $size[SPLASH_DPI]); $image->readImage($_FILES['splash']['tmp_name']); $image->stripImage(); if ($ext == 'jpg') { switch ($_POST['compression']) { case 'low': $cq = 80; break; case 'medium': $cq = 65; break; case 'high': $cq = 50; break; default: $cq = 100;
function setimagesize($imagefile, $width = false, $height = false) { global $enable_imagick; if ($enable_imagick && class_exists('Imagick')) { $im = new Imagick(); $im->setResolution(300, 300); $im->readImage($imagefile); } $attr = imgetimagesize($imagefile); if (!$width && !$height) { return $attr; } if (!$height) { $height = round($attr['height'] * $width / $attr['width']); } if (!$width) { $width = round($attr['width'] * $height / $attr['height']); } return array("width" => $width, "height" => $height, "type" => $attr['type'], "attr" => "width=\"{$width}\" height=\"{$height}\""); }
function pdf_image($load_number) { $imagick = new Imagick(); $imagick->setResolution(200, 200); $imagick->readImage('../tkgo_files2/' . $load_number . '.pdf'); $imagick->extentImage(1700, 2200, 0, 0); $imagick->setImageFormat('jpeg'); $imagick->writeImage('../tkgo_files2/' . $load_number . '.jpg'); }
/** * Process Imagick image stream request, e.g., for a PDF thumbnail * * Requires mla_stream_file (relative to wp_upload_dir ) in $_REQUEST; * optional $_REQUEST parameters are: * mla_stream_width, mla_stream_height, mla_stream_frame, mla_stream_resolution, * mla_stream_quality, mla_stream_type, mla_stream_fit, mla_ghostscript_path * * @since 2.10 * * @return void echos image content and calls exit(); */ public static function mla_process_stream_image() { self::_mla_debug_add('MLAImageProcessor::mla_process_stream_image REQUEST = ' . var_export($_REQUEST, true)); if (!class_exists('Imagick')) { self::_mla_die('Imagick not installed', __LINE__, 500); } if (ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); } $file = $_REQUEST['mla_stream_file']; if (!is_file($file)) { self::_mla_die('File not found', __LINE__, 404); } $use_mutex = isset($_REQUEST['mla_single_thread']); $width = isset($_REQUEST['mla_stream_width']) ? abs(intval($_REQUEST['mla_stream_width'])) : 0; $height = isset($_REQUEST['mla_stream_height']) ? abs(intval($_REQUEST['mla_stream_height'])) : 0; $type = isset($_REQUEST['mla_stream_type']) ? $_REQUEST['mla_stream_type'] : 'image/jpeg'; $quality = isset($_REQUEST['mla_stream_quality']) ? abs(intval($_REQUEST['mla_stream_quality'])) : 0; $frame = isset($_REQUEST['mla_stream_frame']) ? abs(intval($_REQUEST['mla_stream_frame'])) : 0; $resolution = isset($_REQUEST['mla_stream_resolution']) ? abs(intval($_REQUEST['mla_stream_resolution'])) : 72; /* * If mla_ghostscript_path is present, a non-standard GS location can be found in a file written by * the [mla_gallery] shortcode processor. */ $ghostscript_path = isset($_REQUEST['mla_ghostscript_path']) ? $_REQUEST['mla_ghostscript_path'] : ''; if (!empty($ghostscript_path)) { $ghostscript_path = @file_get_contents(dirname(__FILE__) . '/' . 'mla-ghostscript-path.txt'); } if ($use_mutex) { $temp_file = self::_get_temp_file(); @unlink($temp_file); $temp_file = pathinfo($temp_file, PATHINFO_DIRNAME) . '/mla-mutex.txt'; $mutex = new MLAMutex(); $mutex->init(1, $temp_file); $mutex->acquire(); self::_mla_debug_add('MLAImageProcessor::mla_process_stream_image begin file = ' . var_export($file, true)); } /* * Convert the file to an image format and load it */ try { self::$image = 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 * default resolution is 72,72 */ self::$image->setResolution($resolution, $resolution); //$result = false; $result = self::_ghostscript_convert($file, $frame, $resolution, $type, $ghostscript_path); if (false === $result) { try { self::$image->readImage($file . '[' . $frame . ']'); } catch (Exception $e) { self::$image->readImage($file . '[0]'); } if ('image/jpeg' == $type) { $extension = 'JPG'; } else { $extension = 'PNG'; } self::$image->setImageFormat($extension); } if (!self::$image->valid()) { self::_mla_die('File not loaded', __LINE__, 404); } } catch (Exception $e) { self::_mla_die('Image load exception: ' . $e->getMessage(), __LINE__, 404); } /* * Prepare the output image; resize and flatten, if necessary */ try { if (isset($_REQUEST['mla_stream_fit'])) { $best_fit = '1' == $_REQUEST['mla_stream_fit']; } else { $best_fit = false; } self::_prepare_image($width, $height, $best_fit, $type, $quality); } catch (Exception $e) { self::_mla_die('_prepare_image exception: ' . $e->getMessage(), __LINE__, 500); } /* * Stream the image back to the requestor */ try { header("Content-Type: {$type}"); echo self::$image->getImageBlob(); } catch (Exception $e) { self::_mla_die('Image stream exception: ' . $e->getMessage(), __LINE__, 500); } if ($use_mutex) { $mutex->release(); } exit; }
/** * Multile File Upload * * @access public * @param string * @return mixed */ public function do_multi_upload($field, $load_id, $shipments) { //Clear multi_upload_data. $this->_multi_upload_data = array(); //Is $_FILES[$field] set? If not, no reason to continue. if (!isset($_FILES[$field])) { return false; } //Is this really a multi upload? if (!is_array($_FILES[$field]["name"])) { //Fallback to do_upload method. return $this->do_upload($field); } //Is the upload path valid? if (!$this->validate_upload_path()) { //Errors will already be set by validate_upload_path() so just return FALSE return FALSE; } //Every file will have a separate entry in each of the $_FILES associative array elements (name, type, etc). //Loop through $_FILES[$field]["name"] as representative of total number of files. Use count as key in //corresponding elements of the $_FILES[$field] elements. //var to handle file names $number_name = 1; $bol_iter = 0; foreach ($_FILES[$field]["name"] as $i => $v) { //Was the file able to be uploaded? If not, determine the reason why. if (!is_uploaded_file($_FILES[$field]["tmp_name"][$i])) { //Determine error number. $error = !isset($_FILES[$field]["error"][$i]) ? 4 : $_FILES[$field]["error"][$i]; //Set error. switch ($error) { //UPLOAD_ERR_INI_SIZE case 1: $this->set_error("upload_file_exceeds_limit"); break; //UPLOAD_ERR_FORM_SIZE //UPLOAD_ERR_FORM_SIZE case 2: $this->set_error("upload_file_exceeds_form_limit"); break; //UPLOAD_ERR_PARTIAL //UPLOAD_ERR_PARTIAL case 3: $this->set_error("upload_file_partial"); break; //UPLOAD_ERR_NO_FILE //UPLOAD_ERR_NO_FILE case 4: $this->set_error("upload_no_file_selected"); break; //UPLOAD_ERR_NO_TMP_DIR //UPLOAD_ERR_NO_TMP_DIR case 6: $this->set_error("upload_no_temp_directory"); break; //UPLOAD_ERR_CANT_WRITE //UPLOAD_ERR_CANT_WRITE case 7: $this->set_error("upload_unable_to_write_file"); break; //UPLOAD_ERR_EXTENSION //UPLOAD_ERR_EXTENSION case 8: $this->set_error("upload_stopped_by_extension"); break; default: $this->set_error("upload_no_file_selected"); break; } //Return failed upload. return FALSE; } //Set current file data as class variables. $this->file_temp = $_FILES[$field]["tmp_name"][$i]; $this->file_size = $_FILES[$field]["size"][$i]; $this->_file_mime_type($_FILES[$field], $i); $this->file_type = preg_replace("/^(.+?);.*\$/", "\\1", $this->file_type); $this->file_type = strtolower(trim(stripslashes($this->file_type), '"')); $this->file_name = $this->_prep_filename($_FILES[$field]["name"][$i]); $this->file_ext = $this->get_extension($this->file_name); $this->client_name = $this->file_name; //Is the file type allowed to be uploaded? if (!$this->is_allowed_filetype()) { $this->set_error("upload_invalid_filetype"); return FALSE; } //If we're overriding, let's now make sure the new name and type is allowed. //Check if a filename was supplied for the current file. Otherwise, use it's given name. if (!empty($this->_multi_file_name_override[$i])) { $this->file_name = $this->_prep_filename($this->_multi_file_name_override[$i]); //If no extension was provided in the file_name config item, use the uploaded one. if (strpos($this->_multi_file_name_override[$i], ".") === FALSE) { $this->file_name .= $this->file_ext; //An extension was provided, lets have it! } else { $this->file_ext = $this->get_extension($this->_multi_file_name_override[$i]); } if (!$this->is_allowed_filetype(TRUE)) { $this->set_error("upload_invalid_filetype"); return FALSE; } } //Convert the file size to kilobytes. if ($this->file_size > 0) { $this->file_size = round($this->file_size / 1024, 2); } //Is the file size within the allowed maximum? if (!$this->is_allowed_filesize()) { $this->set_error("upload_invalid_filesize"); return FALSE; } //Are the image dimensions within the allowed size? //Note: This can fail if the server has an open_basdir restriction. if (!$this->is_allowed_dimensions()) { $this->set_error("upload_invalid_dimensions"); return FALSE; } //Sanitize the file name for security. // $this->file_name = $this->clean_file_name($this->file_name); //Truncate the file name if it's too long if ($this->max_filename > 0) { $this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename); } //Remove white spaces in the name if ($this->remove_spaces == TRUE) { $this->file_name = preg_replace("/\\s+/", "_", $this->file_name); } /* Validate the file name * This function appends an number onto the end of * the file if one with the same name already exists. * If it returns false there was a problem. */ $this->orig_name = $this->file_name; if ($this->overwrite == FALSE) { $this->file_name = $this->set_filename($this->upload_path, $this->file_name); if ($this->file_name === FALSE) { return FALSE; } } /* Run the file through the XSS hacking filter * This helps prevent malicious code from being * embedded within a file. Scripts can easily * be disguised as images or other file types. */ if ($this->xss_clean) { if ($this->do_xss_clean() === FALSE) { $this->set_error("upload_unable_to_write_file"); return FALSE; } } /* Move the file to the final destination * To deal with different server configurations * we'll attempt to use copy() first. If that fails * we'll use move_uploaded_file(). One of the two should * reliably work in most environments */ //get file extension $array = explode('.', $this->file_name); $exten = end($array); $file_name = $load_id . '_bol_' . $shipments[$bol_iter]->bol_number . '.' . end($array); $file_name_not_ext = $load_id . '_bol_' . $shipments[$bol_iter]->bol_number; // echo 'not ext: '.$file_name_not_ext; $file_route = $this->upload_path . $file_name; //Convert pdf pages to images if (!@copy($this->file_temp, $this->upload_path . $file_name)) { if (!@move_uploaded_file($this->file_temp, $this->upload_path . $this->file_name)) { $this->set_error("upload_destination_error"); return FALSE; } } else { $num = $this->count_pages($file_route); $this->pages_number = $num; $image = new Imagick(); $image->setResolution(200, 200); for ($j = 0; $j < $num; $j++) { //$cont++; $image->readImage($file_route . "[" . $j . "]"); $image->writeImage($this->upload_path . $file_name_not_ext . "-" . $j . ".jpg"); } } $bol_iter++; /* Set the finalized image dimensions * This sets the image width/height (assuming the * file was an image). We use this information * in the "data" function. */ $this->set_image_properties($this->upload_path . $this->file_name); //Set current file data to multi_file_upload_data. $this->set_multi_upload_data(); } //Return all file upload data. return TRUE; }
function salveazaImaginePdf($numeFisier) { define("FOLDER_BULETINE_VECHI", "uploads/buletine-vechi/"); define("FOLDER_BULETINE", "uploads/buletine/"); define("FOLDER_IMAGINI_BULETINE", "uploads/imagini-buletine/"); // Fa thumbnail $im = new Imagick(); $im->setResolution(43, 43); $im->readImage(FOLDER_BULETINE_VECHI . $numeFisier . "[0]"); $im->setImageResolution(100, 100); $im->resampleImage(30, 30, imagick::FILTER_UNDEFINED, 1); $im->setImageFormat("png"); $d = $im->getImageGeometry(); $w = $d['width']; $h = $d['height']; $im->cropImage($w / 2, $h, $w / 2, 0); $caleImaginePdf = FOLDER_IMAGINI_BULETINE . substr($numeFisier, 0, -4) . "-thumb.png"; $im->writeImage($caleImaginePdf); // Pagina 1 $im = new Imagick(); $im->setResolution(300, 300); $im->readImage(FOLDER_BULETINE_VECHI . $numeFisier . "[0]"); $im->setImageResolution(100, 100); $im->resampleImage(30, 30, imagick::FILTER_UNDEFINED, 1); $im->setImageFormat("png"); $d = $im->getImageGeometry(); $w = $d['width']; $h = $d['height']; $im->cropImage($w / 2, $h, $w / 2, 0); $im->writeImage(FOLDER_IMAGINI_BULETINE . substr($numeFisier, 0, -4) . "-pag1.png"); $im->destroy(); // Pagina 4 $im = new Imagick(); $im->setResolution(300, 300); $im->readImage(FOLDER_BULETINE_VECHI . $numeFisier . "[0]"); $im->setImageResolution(100, 100); $im->resampleImage(30, 30, imagick::FILTER_UNDEFINED, 1); $im->setImageFormat("png"); $im->cropImage($w / 2, $h, 0, 0); $im->writeImage(FOLDER_IMAGINI_BULETINE . substr($numeFisier, 0, -4) . "-pag4.png"); $im->destroy(); // Pagina 3 $im = new Imagick(); $im->setResolution(300, 300); $im->readImage(FOLDER_BULETINE_VECHI . $numeFisier . "[1]"); $im->setImageResolution(100, 100); $im->resampleImage(30, 30, imagick::FILTER_UNDEFINED, 1); $im->setImageFormat("png"); $im->cropImage($w / 2, $h, $w / 2, 0); $im->writeImage(FOLDER_IMAGINI_BULETINE . substr($numeFisier, 0, -4) . "-pag3.png"); $im->destroy(); // Pagina 2 $im = new Imagick(); $im->setResolution(300, 300); $im->readImage(FOLDER_BULETINE_VECHI . $numeFisier . "[1]"); $im->setImageResolution(100, 100); $im->resampleImage(30, 30, imagick::FILTER_UNDEFINED, 1); $im->setImageFormat("png"); $im->cropImage($w / 2, $h, 0, 0); $im->writeImage(FOLDER_IMAGINI_BULETINE . substr($numeFisier, 0, -4) . "-pag2.png"); $im->destroy(); return $caleImaginePdf; }