function cdm_thumbPdf($pdf) { if (class_exists('imagick')) { $upload_dir = wp_upload_dir(); $tmp_folder = $upload_dir['basedir'] . '/imageMagick_tmp/'; if (!is_dir($tmp_folder)) { mkdir($tmp_folder, 0777); } $tmp = $tmp_folder; $format = "png"; $source = $pdf; $dest = "" . $pdf . "_big.{$format}"; $dest2 = "" . $pdf . "_small.{$format}"; // read page 1 $im = new imagick('' . $source . '[0]'); // convert to jpg $im->setImageColorspace(255); $im->setImageFormat($format); //resize $im->resizeImage(650, 650, imagick::FILTER_LANCZOS, 1); //write image on server $im->writeImage($dest); //resize $im->resizeImage(250, 250, imagick::FILTER_LANCZOS, 1); //write image on server $im->writeImage($dest2); $im->clear(); $im->destroy(); } else { echo 'php-image-magick not installed. Please disable the pdf thumbnail options or install the php extention correctly.'; exit; } }
public function processPdf($fileNames) { $mpdf = Yii::app()->ePdf->mpdf(); $mpdf->SetImportUse(); $pagecount = $mpdf->SetSourceFile('../' . $fileNames['pdf']); if ($pagecount > 3) { for ($i = 1; $i <= 3; $i++) { if ($i != 1) { $mpdf->AddPage(); } $import_page = $mpdf->ImportPage($i); // add last 3 page $mpdf->UseTemplate($import_page); } } else { $tplId = $mpdf->ImportPage($pagecount); $mpdf->UseTemplate($tplId); } $mpdf->Output('../' . Extensions::FILE_PDF_PREVIEW_PATH . $fileNames['pdfPreview'], 'F'); $im = new imagick(); $im->readimage('/home/notesgen/public_html/' . Extensions::FILE_PDF_PREVIEW_PATH . $fileNames['pdfPreview']); $im->setImageCompressionQuality(0); $im->setImageFormat('jpeg'); $im->writeImage('../' . Extensions::FILE_IMAGE_PATH . $fileNames['image']); $im->setImageCompressionQuality(80); $im->writeImage('../' . Extensions::FILE_IMAGE_PATH_APP . $fileNames['image']); $im->clear(); $im->destroy(); }
function makethumb($srcFile, $dstFile, $dstW, $dstH, $imwf = false) { $im = new imagick($srcFile); $source_w = $im->getImageWidth(); $source_h = $im->getImageHeight(); if ($dstW === 0 && $dstH === 0) { $dstW = $source_w; $dstH = $source_h; } else { // 取得縮在此範圍內的比例 $percent = getResizePercent($source_w, $source_h, $dstW, $dstH); $dstW = $source_w * $percent; $dstH = $source_h * $percent; } $im->thumbnailImage($dstW, $dstH); $im->writeImage($dstFile); $watermarkFile = './logo.png'; if ($imwf && is_file($watermarkFile) && is_file($dstFile)) { $image = new imagick($dstFile); $watermark = new imagick($watermarkFile); $iWidth = $image->getImageWidth(); $iHeight = $image->getImageHeight(); $wWidth = $watermark->getImageWidth(); $wHeight = $watermark->getImageHeight(); if ($iHeight < $wHeight || $iWidth < $wWidth) { $watermark->scaleImage($iWidth, $iHeight); $wWidth = $watermark->getImageWidth(); $wHeight = $watermark->getImageHeight(); } $x = ($iWidth - $wWidth) / 2; $y = ($iHeight - $wHeight) / 2; $image->compositeImage($watermark, imagick::COMPOSITE_OVER, $x, $y); $image->writeImage($dstFile); } }
private function createThumb($filePath, $fileName) { if (!extension_loaded('imagick')) { $errorMessage = "Error: 874"; $this->error($errorMessage); } try { $fileNameWithoutExt = $fileName; $imagePreview = new imagick($this->uploadsDir . $fileName); $imagePreview->scaleImage(300, 0); $imagePreview->writeImage($this->thumbDir . $fileNameWithoutExt); } catch (ImagickException $e) { $errorMessage = "Error: 3435"; $this->error($errorMessage); } return $fileNameWithoutExt; }
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; }
/** * Generate pdf, preview pdf from images uploaded by user. * * @param array $images * * @return array * * @author Kuldeep Dangi <*****@*****.**> */ public function getPdfFromImages($images) { $fileUploadAbsolutePath = Yii::app()->params['FILE_SERVER_IMAGE_PATH'] . self::FILE_UPLOAD_PATH; $pdfUploadAbsolutePath = Yii::app()->params['FILE_SERVER_IMAGE_PATH'] . self::FILE_CONVERT_PATH; $upload_file = array(); $html = $previewHtml = ''; $randomNumber = MD5($this->getRandomNumber()); $savedFileNames = array('image' => $randomNumber . '.jpg', 'imagepdf' => $randomNumber . '.pdf.pdf', 'pdf' => $randomNumber . '.pdf'); $imagesCount = count($images); $imageCounterCount = 1; foreach ($images as $image) { if ($imagesCount > 3 && $imageCounterCount < 4) { $previewHtml .= '<img src="../' . self::FILE_UPLOAD_PATH . $image . '"/>'; } elseif ($imagesCount < 4 && $imageCounterCount == $imagesCount) { $previewHtml .= '<img src="../' . self::FILE_UPLOAD_PATH . $image . '"/>'; } $html .= '<img src="../' . self::FILE_UPLOAD_PATH . $image . '"/>'; $imageCounterCount++; } $mpdf = Yii::app()->ePdf->mpdf(); $mpdf->debug = true; $mpdf->WriteHTML($html); $mpdf->Output('../' . self::FILE_CONVERT_PATH . $savedFileNames['pdf'], 'F'); $mpdf1 = Yii::app()->ePdf->mpdf(); $mpdf1->debug = true; $mpdf1->WriteHTML($previewHtml); $mpdf1->Output('../' . self::FILE_PDF_PREVIEW_PATH . $savedFileNames['imagepdf'], 'F'); $im = new imagick(); $im->readimage('/home/notesgen/public_html/' . self::FILE_PDF_PREVIEW_PATH . $savedFileNames['imagepdf']); $im->setImageCompressionQuality(0); $im->setImageFormat('jpeg'); $im->writeImage('../' . self::FILE_IMAGE_PATH . $savedFileNames['image']); $im->setImageCompressionQuality(80); $im->writeImage('../' . self::FILE_IMAGE_PATH_APP . $savedFileNames['image']); $im->clear(); $im->destroy(); return $savedFileNames; }
/* Font properties */ $draw3->setFont($signatureFont); $draw3->setFontSize($signatureSize); $draw3->setFontWeight(400); // change wordwrap depending on font size switch ($signatureSize) { case 20: $signatureWordwrap = 24; break; case 22: $signatureWordwrap = 23; break; case 24: $signatureWordwrap = 21; break; case 26: $signatureWordwrap = 19; break; case 28: $signatureWordwrap = 17; break; case 30: $signatureWordwrap = 16; break; } $fixedCardSignature = wordwrap($cardSignature, $signatureWordwrap, "\n"); $b->annotateImage($draw3, 340, 300, 0, $fixedCardSignature); $imgName = "images/usercards/test-image.png"; $b->writeImage($imgName); // Redirect to results page header("Location: http://sometestsite.com/christmas-card-maker/viewcard.php");
/** * 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; } }
$wbshell1 = "xvfb-run --server-args=\"-screen 0, 1024x768x24\" cutycapt --min-width=460 --url=" . $site_url . " --out=" . $img_name; $wbshell2 = "xvfb-run --server-args=\"-screen 0, 1024x768x24\" cutycapt --min-width=1024 --url=" . $site_url . " --out=" . $img_name; } } //根据生成图片的大小调用语句 $wbshell = $picsize == 1 ? $wbshell1 : $wbshell2; //执行截图语句 system($wbshell); //exec($wbshell); //注:下面的操作仅是对图片进一步进行调整,可以缩小图片体积等,并方便更多的处理,并非必须。 $im = new imagick($img_name); //if($picsize==1) $im->resizeImage(490,0,Imagick::FILTER_LANCZOS,1); $im->setImageFormat("png"); $im->setCompressionQuality(90); $img_name2 = 'html2png/' . time() . '.png'; $im->writeImage($img_name2); $im->clear(); $im->destroy(); //输出图片连接 $url_this = dirname('http://' . $_SERVER['SERVER_NAME'] . $_SERVER["REQUEST_URI"]) . '/' . $img_name2; } else { $url_this = dirname('http://' . $_SERVER['SERVER_NAME'] . $_SERVER["REQUEST_URI"]) . '/google.png'; } ?> <div class="wrapper" > <h1>内容生成工具</h1> <ul> <li><?php echo $errinfo; ?> </li>
/** * Rotate image * * @param string $path image file * @param int $degree rotete degrees * @param string $bgcolor square background color in #rrggbb format * @param string $destformat image destination format * @return string|false * @author nao-pon * @author Troex Nevelin **/ protected function imgRotate($path, $degree, $bgcolor = '#ffffff', $destformat = null) { if (($s = @getimagesize($path)) == false || $degree % 360 === 0) { return false; } $result = false; // try lossless rotate if ($degree % 90 === 0 && in_array($s[2], array(IMAGETYPE_JPEG, IMAGETYPE_JPEG2000))) { $count = $degree / 90 % 4; $exiftran = array(1 => '-9', 2 => '-1', 3 => '-2'); $jpegtran = array(1 => '90', 2 => '180', 3 => '270'); $quotedPath = escapeshellarg($path); $cmds = array('exiftran -i ' . $exiftran[$count] . ' ' . $path, 'jpegtran -rotate ' . $jpegtran[$count] . ' -copy all -outfile ' . $quotedPath . ' ' . $quotedPath); foreach ($cmds as $cmd) { if ($this->procExec($cmd) === 0) { $result = true; break; } } if ($result) { return $path; } } switch ($this->imgLib) { case 'imagick': try { $img = new imagick($path); } catch (Exception $e) { return false; } $img->rotateImage(new ImagickPixel($bgcolor), $degree); $result = $img->writeImage($path); $img->destroy(); return $result ? $path : false; break; case 'gd': $img = self::gdImageCreate($path, $s['mime']); $degree = 360 - $degree; list($r, $g, $b) = sscanf($bgcolor, "#%02x%02x%02x"); $bgcolor = imagecolorallocate($img, $r, $g, $b); $tmp = imageRotate($img, $degree, (int) $bgcolor); $result = self::gdImage($tmp, $path, $destformat, $s['mime']); imageDestroy($img); imageDestroy($tmp); return $result ? $path : false; break; } return false; }
public function _resizeImagick(Model $model, $field, $path, $size, $geometry, $thumbnailPath) { $srcFile = $path . $model->data[$model->alias][$field]; $pathInfo = $this->_pathinfo($srcFile); $thumbnailType = $imageFormat = $this->settings[$model->alias][$field]['thumbnailType']; $isMedia = $this->_isMedia($model, $this->runtime[$model->alias][$field]['type']); $image = new imagick(); if ($isMedia) { $image->setResolution(300, 300); $srcFile = $srcFile . '[0]'; } $image->readImage($srcFile); $height = $image->getImageHeight(); $width = $image->getImageWidth(); if (preg_match('/^\\[[\\d]+x[\\d]+\\]$/', $geometry)) { // resize with banding list($destW, $destH) = explode('x', substr($geometry, 1, strlen($geometry) - 2)); $image->thumbnailImage($destW, $destH, true); $imageGeometry = $image->getImageGeometry(); $x = ($imageGeometry['width'] - $destW) / 2; $y = ($imageGeometry['height'] - $destH) / 2; $image->setGravity(Imagick::GRAVITY_CENTER); $image->extentImage($destW, $destH, $x, $y); } elseif (preg_match('/^[\\d]+x[\\d]+$/', $geometry)) { // cropped resize (best fit) list($destW, $destH) = explode('x', $geometry); $image->cropThumbnailImage($destW, $destH); } elseif (preg_match('/^[\\d]+w$/', $geometry)) { // calculate heigh according to aspect ratio $image->thumbnailImage((int) $geometry - 1, 0); } elseif (preg_match('/^[\\d]+h$/', $geometry)) { // calculate width according to aspect ratio $image->thumbnailImage(0, (int) $geometry - 1); } elseif (preg_match('/^[\\d]+l$/', $geometry)) { // calculate shortest side according to aspect ratio $destW = 0; $destH = 0; $destW = $width > $height ? (int) $geometry - 1 : 0; $destH = $width > $height ? 0 : (int) $geometry - 1; $imagickVersion = phpversion('imagick'); $image->thumbnailImage($destW, $destH, !($imagickVersion[0] == 3)); } if ($isMedia) { $thumbnailType = $imageFormat = $this->settings[$model->alias][$field]['mediaThumbnailType']; } if (!$thumbnailType || !is_string($thumbnailType)) { try { $thumbnailType = $imageFormat = $image->getImageFormat(); // Fix file casing while (true) { $ext = false; $pieces = explode('.', $srcFile); if (count($pieces) > 1) { $ext = end($pieces); } if (!$ext || !strlen($ext)) { break; } $low = array('ext' => strtolower($ext), 'thumbnailType' => strtolower($thumbnailType)); if ($low['ext'] == 'jpg' && $low['thumbnailType'] == 'jpeg') { $thumbnailType = $ext; break; } if ($low['ext'] == $low['thumbnailType']) { $thumbnailType = $ext; } break; } } catch (Exception $e) { $this->log($e->getMessage(), 'upload'); $thumbnailType = $imageFormat = 'png'; } } $fileName = str_replace(array('{size}', '{filename}', '{primaryKey}'), array($size, $pathInfo['filename'], $model->id), $this->settings[$model->alias][$field]['thumbnailName']); $destFile = "{$thumbnailPath}{$fileName}.{$thumbnailType}"; $image->setImageCompressionQuality($this->settings[$model->alias][$field]['thumbnailQuality']); $image->setImageFormat($imageFormat); if (!$image->writeImage($destFile)) { return false; } $image->clear(); $image->destroy(); return true; }
/** * Rotate image * * @param string $path image file * @param int $degree rotete degrees * @param string $bgcolor square background color in #rrggbb format * @param string $destformat image destination format * @return string|false * @author nao-pon * @author Troex Nevelin **/ protected function imgRotate($path, $degree, $bgcolor = '#ffffff', $destformat = null) { if (($s = @getimagesize($path)) == false) { return false; } $result = false; switch ($this->imgLib) { case 'imagick': try { $img = new imagick($path); } catch (Exception $e) { return false; } $img->rotateImage(new ImagickPixel($bgcolor), $degree); $result = $img->writeImage($path); return $result ? $path : false; break; case 'gd': if ($s['mime'] == 'image/jpeg') { $img = imagecreatefromjpeg($path); } elseif ($s['mime'] == 'image/png') { $img = imagecreatefrompng($path); } elseif ($s['mime'] == 'image/gif') { $img = imagecreatefromgif($path); } elseif ($s['mime'] == 'image/xbm') { $img = imagecreatefromxbm($path); } $degree = 360 - $degree; list($r, $g, $b) = sscanf($bgcolor, "#%02x%02x%02x"); $bgcolor = imagecolorallocate($img, $r, $g, $b); $tmp = imageRotate($img, $degree, (int) $bgcolor); if ($destformat == 'jpg' || $destformat == null && $s['mime'] == 'image/jpeg') { $result = imagejpeg($tmp, $path, 100); } else { if ($destformat == 'gif' || $destformat == null && $s['mime'] == 'image/gif') { $result = imagegif($tmp, $path, 7); } else { $result = imagepng($tmp, $path, 7); } } imageDestroy($img); imageDestroy($tmp); return $result ? $path : false; break; } return false; }
if ($p[1] != 'gif') { // Открываем watermark $watermark = new imagick('./img/watermark.png'); // узнаем размеры оригинального изображения $im_width = $im->getImageWidth(); $im_height = $im->getImageHeight(); // узнаем размеры водяного знака $watermark_width = $watermark->getImageWidth(); $watermark_height = $watermark->getImageHeight(); // посчитать x и y $left = $im_width - $watermark_width - 10; $top = $im_height - $watermark_height - 10; // накладываем watermark на оригинальное изображение $im->compositeImage($watermark, imagick::COMPOSITE_OVER, $left, $top); // сохраняем оригинал $im->writeImage('./images/' . $image_name . '.' . $p[1]); } else { // сохраняем .gif с учетом анимации $im->writeImages('./images/' . $image_name . '.' . $p[1], true); } // Копируем объект для различных типов $large = $im->clone(); $square = $im->clone(); // Создаем квадратное изображение 160x160 px $square->cropThumbnailImage(160, 160); $square->writeImage('./images/' . $image_name . 's' . '.' . $p[1]); // Создаем большое изображение с шириной 640 px и переменной высотой $large->thumbnailImage(640, 0); $large->writeImage('./images/' . $image_name . 'l' . '.' . $p[1]); // добавляем имя, расширение, дату загрузки изображения в БД // выбираем коллекцию
private function greateTH($file, $th) { $im = new imagick($_SERVER['DOCUMENT_ROOT'] . "/" . $file); $im->cropThumbnailImage(110, 110); $im->writeImage($_SERVER['DOCUMENT_ROOT'] . "/" . $th); }
/** * Rotate image * * @param string $path image file * @param int $degree rotete degrees * @param string $bgcolor square background color in #rrggbb format * @param string $destformat image destination format * @return string|false * @author nao-pon * @author Troex Nevelin **/ protected function imgRotate($path, $degree, $bgcolor = '#ffffff', $destformat = null) { if (($s = @getimagesize($path)) == false) { return false; } $result = false; switch ($this->imgLib) { case 'imagick': try { $img = new imagick($path); } catch (Exception $e) { return false; } $img->rotateImage(new ImagickPixel($bgcolor), $degree); $result = $img->writeImage($path); return $result ? $path : false; break; case 'gd': $img = self::gdImageCreate($path, $s['mime']); $degree = 360 - $degree; list($r, $g, $b) = sscanf($bgcolor, "#%02x%02x%02x"); $bgcolor = imagecolorallocate($img, $r, $g, $b); $tmp = imageRotate($img, $degree, (int) $bgcolor); $result = self::gdImage($tmp, $path, $destformat, $s['mime']); imageDestroy($img); imageDestroy($tmp); return $result ? $path : false; break; } return false; }
/** * Resize image * * @param string $img image path * @param int $w image width * @param int $h image height * @return bool **/ protected function _resizeImg($img, $w, $h) { if (false == ($s = getimagesize($img))) { return false; } switch ($this->_options['imgLib']) { case 'imagick': if (false != ($_img = new imagick($img))) { return $_img->cropThumbnailImage($w, $h) && $_img->writeImage($img); } break; case 'mogrify': exec('mogrify -scale ' . $w . 'x' . $h . '! ' . escapeshellarg($img), $o, $c); return 0 == $c; break; case 'gd': if ($s['mime'] == 'image/jpeg') { $_img = imagecreatefromjpeg($img); } elseif ($s['mime'] = 'image/png') { $_img = imagecreatefrompng($img); } elseif ($s['mime'] = 'image/gif') { $_img = imagecreatefromgif($img); } if (!$_img || false == ($_out = imagecreatetruecolor($w, $h))) { return false; } if (!imagecopyresampled($_out, $_img, 0, 0, 0, 0, $w, $h, $s[0], $s[1])) { return false; } if ($s['mime'] == 'image/jpeg') { $r = imagejpeg($_out, $img, 100); } else { if ($s['mime'] = 'image/png') { $r = imagepng($_out, $img, 7); } else { $r = imagegif($_out, $img, 7); } } imagedestroy($_img); imagedestroy($_out); return $r; break; } }
//show_img, save_img $cropThumbnailImage = true; $filename = "img/" . $_GET["file"]; if (class_exists("imagick")) { $im = new imagick($filename); /* create the thumbnail */ if ($cropThumbnailImage) { $im->cropThumbnailImage(80, 80); } /* Write to a file */ if ($resizeImage) { $im->resizeImage(900, 80, 1, 0.5); } switch ($case) { case "write_img": $im->writeImage("img/" . $_GET["file"]); break; case "show_img": header("Content-Type: image/jpg"); echo $im->getImageBlob(); break; } } else { cropImage_common($filename, 80, 80); } function cropImage_common($filename, $width, $height) { // Content type header('Content-Type: image/jpeg'); // Cacul des nouvelles dimensions list($width_orig, $height_orig) = getimagesize($filename);
/** * Crop image * * @param string $path image file * @param int $width crop width * @param int $height crop height * @param bool $x crop left offset * @param bool $y crop top offset * @param string $destformat image destination format * @return string|false * @author Dmitry (dio) Levashov, Alexey Sukhotin **/ protected function imgCrop($path, $width, $height, $x, $y, $destformat = null) { if (($s = @getimagesize($path)) == false) { return false; } $result = false; $this->rmTmb($path); switch ($this->imgLib) { case 'imagick': try { $img = new imagick($path); } catch (Exception $e) { return false; } $img->cropImage($width, $height, $x, $y); $result = $img->writeImage($path); return $result ? $path : false; break; case 'gd': if ($s['mime'] == 'image/jpeg') { $img = imagecreatefromjpeg($path); } elseif ($s['mime'] == 'image/png') { $img = imagecreatefrompng($path); } elseif ($s['mime'] == 'image/gif') { $img = imagecreatefromgif($path); } elseif ($s['mime'] == 'image/xbm') { $img = imagecreatefromxbm($path); } if ($img && false != ($tmp = imagecreatetruecolor($width, $height))) { if (!imagecopy($tmp, $img, 0, 0, $x, $y, $width, $height)) { return false; } if ($destformat == 'jpg' || $destformat == null && $s['mime'] == 'image/jpeg') { $result = imagejpeg($tmp, $path, 100); } else { if ($destformat == 'gif' || $destformat == null && $s['mime'] == 'image/gif') { $result = imagegif($tmp, $path, 7); } else { $result = imagepng($tmp, $path, 7); } } imagedestroy($img); imagedestroy($tmp); return $result ? $path : false; } break; } return false; }
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);
/** * @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; }
<?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;
private function resize_imagick($src, $width, $height, $quality, $preserveExif) { try { $img = new imagick($src); if (strtoupper($img->getImageFormat()) === 'JPEG') { $img->setImageCompression(imagick::COMPRESSION_JPEG); $img->setImageCompressionQuality($quality); if (!$preserveExif) { try { $orientation = $img->getImageOrientation(); } catch (ImagickException $e) { $orientation = 0; } $img->stripImage(); if ($orientation) { $img->setImageOrientation($orientation); } } } $img->resizeImage($width, $height, Imagick::FILTER_LANCZOS, true); $result = $img->writeImage($src); $img->clear(); $img->destroy(); return $result ? true : false; } catch (Exception $e) { return false; } }
/** * 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; }
function _resizeImagick(&$model, $field, $path, $size, $geometry, $thumbnailPath) { $srcFile = $path . $model->data[$model->alias][$field]; $pathInfo = $this->_pathinfo($srcFile); $thumbnailType = $this->settings[$model->alias][$field]['thumbnailType']; $isMedia = $this->_isMedia($model, $this->runtime[$model->alias][$field]['type']); $image = new imagick(); if ($isMedia) { $image->setResolution(300, 300); $srcFile = $srcFile . '[0]'; } $image->readImage($srcFile); $height = $image->getImageHeight(); $width = $image->getImageWidth(); if (preg_match('/^\\[[\\d]+x[\\d]+\\]$/', $geometry)) { // resize with banding list($destW, $destH) = explode('x', substr($geometry, 1, strlen($geometry) - 2)); $image->thumbnailImage($destW, $destH); } elseif (preg_match('/^[\\d]+x[\\d]+$/', $geometry)) { // cropped resize (best fit) list($destW, $destH) = explode('x', $geometry); $image->cropThumbnailImage($destW, $destH); } elseif (preg_match('/^[\\d]+w$/', $geometry)) { // calculate heigh according to aspect ratio $image->thumbnailImage((int) $geometry - 1, 0); } elseif (preg_match('/^[\\d]+h$/', $geometry)) { // calculate width according to aspect ratio $image->thumbnailImage(0, (int) $geometry - 1); } elseif (preg_match('/^[\\d]+l$/', $geometry)) { // calculate shortest side according to aspect ratio $destW = 0; $destH = 0; $destW = $width > $height ? (int) $geometry - 1 : 0; $destH = $width > $height ? 0 : (int) $geometry - 1; $imagickVersion = phpversion('imagick'); $image->thumbnailImage($destW, $destH, !($imagickVersion[0] == 3)); } if ($isMedia) { $thumbnailType = $this->settings[$model->alias][$field]['mediaThumbnailType']; } if (!$thumbnailType || !is_string($thumbnailType)) { try { $thumbnailType = $image->getImageFormat(); } catch (Exception $e) { $thumbnailType = 'png'; } } $fileName = str_replace(array('{size}', '{filename}'), array($size, $pathInfo['filename']), $this->settings[$model->alias][$field]['thumbnailName']); $destFile = "{$thumbnailPath}{$fileName}.{$thumbnailType}"; $image->setImageCompressionQuality($this->settings[$model->alias][$field]['thumbnailQuality']); $image->setImageFormat($thumbnailType); if (!$image->writeImage($destFile)) { return false; } $image->clear(); $image->destroy(); return true; }
/** * 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; }
public function uploadfile() { $folder = isset($_GET['folder']) ? $_GET['folder'] : 'others'; $targetFolder = "/upload_file/{$folder}"; $prefix = time(); $setting = $this->general_model->get_email_from_setting(); $type = explode(",", $setting[0]['download_type']); foreach ($type as $key => $value) { $type[$key] = strtolower($value); } $userid = $_SESSION['user']['user_id']; if (!empty($_FILES)) { $_FILES["Filedata"]["name"] = str_replace(' ', '', $_FILES["Filedata"]["name"]); $_FILES["Filedata"]["tmp_name"] = str_replace(' ', '', $_FILES["Filedata"]["tmp_name"]); $uploaddatafile1 = md5($_FILES["Filedata"]["name"]); $tempFile = $_FILES["Filedata"]["tmp_name"]; $targetPath = $_SERVER["DOCUMENT_ROOT"] . $targetFolder; $targetFile = rtrim($targetPath, "/") . "/" . $_FILES["Filedata"]["name"]; $fileTypes = $type; //array("zip","rar"); $fileParts = pathinfo($_FILES["Filedata"]["name"]); if (in_array(strtolower($fileParts["extension"]), $fileTypes)) { move_uploaded_file($tempFile, $targetFile); if (isset($_GET['w'])) { $w = $_GET['w']; } else { $w = 100; } if (isset($_GET['h'])) { $h = $_GET['h']; } else { $h = 100; } $path_upload = "upload_file/{$folder}/" . $_FILES["Filedata"]["name"]; $root = dirname(dirname(dirname(__FILE__))); $file = '/' . $path_upload; //a reference to the file in reference to the current working directory. // Process for image $image_info = @getimagesize(base_url() . $path_upload); if (!empty($image_info)) { $image = true; } else { $image = false; } if ($image) { if (!isset($_SESSION['fileuploadname'])) { $_SESSION['fileuploadname'] = $_FILES["Filedata"]["name"]; $_SESSION['fileuploadhtml'] = ''; } else { if (empty($_SESSION['fileuploadname'])) { $_SESSION['fileuploadname'] = $_FILES["Filedata"]["name"]; $_SESSION['fileuploadhtml'] = ''; } } $_SESSION['fileuploadhtml'] .= '<img src="' . base_url() . $path_upload . '" style="width:850px;"/>'; echo "2"; exit; } include $root . "/mpdf/mpdf.php"; require_once $root . "/scribd.php"; $scribd_api_key = "766ydp7ellofhr7x027wl"; $scribd_secret = "sec-7zrz2fxxa2chak965tbp67npqw"; $scribd = new Scribd($scribd_api_key, $scribd_secret); $doc_type = null; $access = "private"; $rev_id = null; $data = $scribd->upload($file, $doc_type, $access, $rev_id); if (!empty($data)) { $result = 0; while ($result == 0) { echo $result = $scribd->getDownloadLinks($data['doc_id']); } file_put_contents('/upload_file/files/c' . $uploaddatafile1 . ".pdf", fopen($result["download_link"], 'r')); //file_put_contents( fopen($result["download_link"], 'r')); $mpdf = new mPDF(); $mpdf->SetImportUse(); $pagecount = $mpdf->SetSourceFile('/upload_file/files/r' . $uploaddatafile1 . ".pdf"); $tplId = $mpdf->ImportPage(1); $mpdf->UseTemplate($tplId); $mpdf->SetDisplayMode('fullpage'); $mpdf->SetWatermarkText(' '); $mpdf->watermark_font = 'DejaVuSansCondensed'; $mpdf->showWatermarkText = true; $md5 = $uploaddatafile1; $mpdf->Output('/upload_file/files/' . $md5 . '.pdf', ''); $mpdf->Thumbnail('/upload_file/files/' . $md5 . '.pdf', 1); $mpdf->Output('/upload_file/files/' . $md5 . '.pdf', ''); unlink('/upload_file/files/c' . $uploaddatafile1 . ".pdf"); $im = new imagick(); $im->readimage('/upload_file/files/' . $md5 . '.pdf'); //$im->readimage('/upload_file/files/'.$md5.'.pdf'); $im->setImageCompressionQuality(0); $im->setImageFormat('jpeg'); $im->writeImage('/upload_file/images/r' . $md5 . '.jpg'); $this->db->set('id', $userid); $this->db->set('fullpdf', '/upload_file/files/r' . $uploaddatafile1 . '.pdf'); $this->db->set('pdf', '/upload_file/files/' . $md5 . '.pdf'); $this->db->set('image', '/upload_file/images/r' . $md5 . '.jpg'); $this->db->insert('scribe'); $im->clear(); $im->destroy(); echo $path_upload . '|' . serialize($data) . '|upload_file/images/r' . $md5 . '.jpg|upload_file/files/' . $uploaddatafile1 . '.pdf'; // echo $path_upload.'|'.serialize($data).'|upload_file/images/'.$md5.'.jpg |upload_file/files/'.$md5.'.pdf'; //echo $path_upload.'|'.serialize($data).'|upload_file/files/cc'.$md5.'.pdf|upload_file/files/'.$md5.'.pdf'; //echo $path_upload.'|'.serialize($data).'|upload_file/images/'.$md5.'.jpg |upload_file/files/'.$_FILES["Filedata"]["name"].'.pdf'; //echo $path_upload.'|'.serialize($data).'|upload_file/images/img'.$md5.'.jpg'; // $_SESSION['scriptfile']= ('/upload_file/files/r'.$uploaddatafile1.".pdf"); //echo $path_upload.'|upload_file/files/c'.$filedata.'.pdf'; //$_SESSION['imagedata']= ('upload_file/images/img'.$md5.'.jpg'); } else { echo "1"; } } else { echo "1"; } } }
public static function resize($orig_file_path, $settings, $target_file_path) { $quality = 95; $crop = $settings['crop_method']; $current_width = $settings['width']; $current_height = $settings['height']; $target_width = min($current_width, $settings['width_requested']); $target_height = min($current_height, $settings['height_requested']); if ($crop) { $x_ratio = $target_width / $current_width; $y_ratio = $target_height / $current_height; $ratio = min($x_ratio, $y_ratio); $use_x_ratio = $x_ratio == $ratio; $new_width = $use_x_ratio ? $target_width : floor($current_width * $ratio); $new_height = !$use_x_ratio ? $target_height : floor($current_height * $ratio); } else { $new_width = $target_width; $new_height = $target_height; } $im = new imagick($orig_file_path); $im->cropThumbnailImage($new_width, $new_height); $im->setImageCompression(imagick::COMPRESSION_JPEG); $im->setImageCompressionQuality($quality); $im->stripImage(); $result = $im->writeImage($target_file_path); $im->destroy(); return array($new_width, $new_height, $target_width, $target_height); }