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;
}
Exemple #2
0
 /**
  * Associates the model with the file
  * @param string $filePath
  * @return boolean
  */
 public function setFile($filePath)
 {
     if (!file_exists($filePath)) {
         return false;
     }
     $info = getimagesize($filePath);
     $imageWidth = $info[0];
     $imageHeight = $info[1];
     $image = new Imagick();
     $image->readimage($filePath);
     $image->setResourceLimit(Imagick::RESOURCETYPE_MEMORY, 1);
     $maxSize = 1920;
     if ($imageWidth > $maxSize && $imageWidth > $imageHeight) {
         $image->thumbnailimage($maxSize, null);
     } elseif ($imageHeight > $maxSize && $imageHeight > $imageWidth) {
         $image->thumbnailimage(null, $maxSize);
     }
     $image->setCompression(Imagick::COMPRESSION_JPEG);
     $image->setCompressionQuality(80);
     $image->stripimage();
     $this->size = filesize($filePath);
     $this->type = $info['mime'];
     $this->width = $info[0];
     $this->height = $info[1];
     $this->content = $image->getImageBlob();
     $this->expireAt(time() + static::EXP_DAY);
     return true;
 }
 public function it_should_be_able_to_load_metadata(Filesystem $filesystem, \Imagick $imagick)
 {
     $file = new LocalFile($this->file);
     $imagick->readimage($this->file)->shouldBeCalled();
     $imagick->identifyimage()->willReturn(['key' => 'value']);
     $imagick->getimageproperties('*SpotColor*')->willReturn([1]);
     $imagick->clear()->shouldBeCalled();
     $this->getMetadataForFile($file, ['extended' => true])->shouldReturn(['key' => 'value', 'hasSpotColors' => true]);
 }
function resize_image($job, $args)
{
    $wrk = $job->workload();
    $data = unserialize($wrk);
    if (!$data['src'] || !$data['dest'] || !$data['x']) {
        $job->sendFail();
        print_r($data);
        return;
    }
    echo $job->handle() . " - creating: {$data['dest']} x:{$data['x']} y:{$data['y']}\n";
    $im = new Imagick();
    $im->readimage($data['src']);
    $im->thumbnailImage($data['x'], $data['y']);
    $im->writeImage($data['dest']);
    $im->destroy();
    $job->sendStatus(1, 1);
    return $data['dest'];
}
<?php

/****
- Read images from resource directory and resize them
- Crop an image from the resized images
- From the crop images, create an image with exact dimensions putting the crop image at the center
  if it is smaller than the defined dimensions. (this is what I needed)
*****/
$resource_dir = '/Library/WebServer/Documents/testdir/';
$files = scandir($resource_dir);
foreach ($files as $file) {
    $image_promo = new Imagick();
    try {
        $image_promo->readimage($resource_dir . $file);
        $image_promo->setImageCompressionQuality(100);
        $image_promo->resizeImage(334, 0, Imagick::FILTER_LANCZOS, 0.9);
        $image_promo->writeImage($resource_dir . "resize/" . $file);
        $image_promo->destroy();
        $image_promo = new Imagick();
        $image_promo->readimage($resource_dir . "resize/" . $file);
        $image_promo->cropImage(334, 181, 0, 0);
        $image_promo->setImageCompressionQuality(100);
        $image_promo->writeImage($resource_dir . "crop/" . $file);
        $image_promo->destroy();
        echo exec('/opt/local/bin/convert ' . $resource_dir . 'crop/' . $file . ' -background white -gravity center -extent 334x181 ' . $resource_dir . 'crop2/' . $file);
    } catch (Exception $e) {
        echo $e->getMessage() . '<br/>';
    }
}
Exemple #6
0
    }
    imagefttext($im, 19, 0, $hoffset + 2, $voffset + 84, $black, $fontc, $team1info[2]);
    imagefttext($im, 19, 0, $hoffset, $voffset + 82, $white, $fontc, $team1info[2]);
    imagefttext($im, 19, 0, $hoffset + 2, $voffset + 84 + $spacing, $black, $fontc, $team2info[2]);
    imagefttext($im, 19, 0, $hoffset, $voffset + 82 + $spacing, $white, $fontc, $team2info[2]);
    $arenainfo = explode(",", $row["col2"]);
    imagefttext($im, 19, 0, 82, 415, $black, $font, $arenainfo[0]);
    imagefttext($im, 19, 0, 80, 413, $white, $font, $arenainfo[0]);
    imagefttext($im, 19, 0, 67, 445, $black, $font, $row["col3"]);
    imagefttext($im, 19, 0, 65, 443, $white, $font, $row["col3"]);
    imagefttext($im, 19, 0, 192, 445, $black, $font, $arenainfo[1]);
    imagefttext($im, 19, 0, 190, 443, $white, $font, $arenainfo[1]);
}
$query = "REPLACE INTO cache SET `key` = '{$key}', `hash` = '{$hash}';";
$result = mysql_query($query) or die("<b>YOU DID SOMETHING WRONG YOU IDIOT</b>.\n<br />Query: " . $query . "<br />\nError: (" . mysql_errno() . ") " . mysql_error());
header('Content-Type: image/png');
imagealphablending($im, false);
imagesavealpha($im, true);
$savepath = "pngout/" . $row["filename"] . '.png';
imagepng($im, $savepath);
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
echo "???";
flush();
$magick = new Imagick();
$magick->readimage(realpath("pngout/" . $row["filename"] . '.png'));
$magick->setImageFormat("tga");
//$magick->scaleImage(480,$row["height"]);
//$magick->borderImage(none,80,0);
$magick->writeImage("out/" . $row["filename"] . '.tga');
 /**
  * @param  $image
  * @return Pimcore_Image_Adapter_Imagick
  */
 public function applyMask($image)
 {
     $image = ltrim($image, "/");
     $image = PIMCORE_DOCUMENT_ROOT . "/" . $image;
     if (is_file($image)) {
         $this->resource->setImageMatte(1);
         $newImage = new Imagick();
         $newImage->readimage($image);
         $newImage->resizeimage($this->getWidth(), $this->getHeight(), Imagick::FILTER_UNDEFINED, 1, false);
         $this->resource->compositeImage($newImage, Imagick::COMPOSITE_DSTIN, 0, 0);
     }
     $this->reinitializeImage();
     return $this;
 }
Exemple #8
0
}
// Using Php connect to Meteor MongDB
$server = "mongodb://127.0.0.1:3001";
$connection = new Mongo($server);
$db = $connection->meteor;
$collection = $db->data;
$collection_backup = $db->backup;
$dir_to_save = "gifFrame/";
$head_name = explode(".", $target_file);
$new_name = $head_name[0];
// check the type of file is gif or not
if (!is_dir($dir_to_save)) {
    mkdir($dir_to_save);
}
$picture = new Imagick();
$picture->readimage($target_file);
$i = 0;
$path_array = [];
$img_byte_array = [];
$img_backup = [];
foreach ($picture as $frame) {
    $frame->setImageAlphaChannel(11);
    $frame->setImageBackgroundColor('white');
    $frame->setImageFormat("jpg");
    $f = $new_name . $i . '.jpg';
    $frame->stripImage();
    $frame->writeImage($dir_to_save . $f);
    $path_array[$i] = $dir_to_save . $f;
    $i++;
}
$de_index = 0;
Exemple #9
0
 /**
  * Load a PDF for use on the printer
  *
  * @param string $pdfFile The file to load
  * @param string $pageWidth The width, in pixels, of the printer's output. The first page of the PDF will be scaled to approximately fit in this area.
  * @param array $range array indicating the first and last page (starting from 0) to load. If not set, the entire document is loaded.
  * @throws Exception Where Imagick is not loaded, or where a missing file or invalid page number is requested.
  * @return multitype:EscposImage Array of images, retrieved from the PDF file.
  */
 public static function loadPdf($pdfFile, $pageWidth = 550, array $range = null)
 {
     if (!extension_loaded('imagick')) {
         throw new Exception(__FUNCTION__ . " requires imagick extension.");
     }
     /*
      * Load first page at very low density (resolution), to figure out what
      * density to use to achieve $pageWidth
      */
     try {
         $image = new Imagick();
         $testRes = 2;
         // Test resolution
         $image->setresolution($testRes, $testRes);
         $image->readimage($pdfFile . "[0]");
         $geo = $image->getimagegeometry();
         $image->destroy();
         $width = $geo['width'];
         $newRes = $pageWidth / $width * $testRes;
         /* Load actual document (can be very slow!) */
         $rangeStr = "";
         // Set to [0] [0-1] page range if $range is set
         if ($range != null) {
             if (count($range) != 2 || !isset($range[0]) || !is_integer($range[0]) || !isset($range[1]) || !is_integer($range[1]) || $range[0] > $range[1]) {
                 throw new Exception("Invalid range. Must be two numbers in the array: The start and finish page indexes, starting from 0.");
             }
             $rangeStr = "[" . ($range[0] == $range[1] ? $range[0] : implode($range, "-")) . "]";
         }
         $image->setresolution($newRes, $newRes);
         $image->readImage($pdfFile . "{$rangeStr}");
         $pages = $image->getNumberImages();
         /* Convert images to Escpos objects */
         $ret = array();
         for ($i = 0; $i < $pages; $i++) {
             $image->setIteratorIndex($i);
             $ep = new EscposImage();
             $ep->readImageFromImagick($image);
             $ret[] = $ep;
         }
         return $ret;
     } catch (ImagickException $e) {
         // Wrap in normal exception, so that classes which call this do not themselves require imagick as a dependency.
         throw new Exception($e);
     }
 }
Exemple #10
0
 /**
  * 合并两张图片(把图二合并到图一来) (ImageMagick 有个奇怪的问题,第一次运行会有点慢)
  * TODO GIF动画
  * @param string $onePath
  *            需要合并的图片一
  * @param string $twoPath
  *            需要合并的图片二
  * @param string $dstPath
  *            合并后的保存地址
  * @param integer $x
  *            合并坐标轴x
  * @param integer $y
  *            合并坐标轴y
  * @return boolean
  */
 public function join($onePath, $twoPath, $dstPath, $x = 0, $y = 0)
 {
     $im1 = new Imagick();
     $im1->readimage($onePath);
     $im2 = new Imagick($twoPath);
     $im2->setimageformat('png');
     $composite = $im2->getImageCompose();
     $im1->compositeimage($im2, $composite, $x, $y);
     $im2->destroy();
     return $im1->writeImage($dstPath);
 }
Exemple #11
0
 $dir = dirname(__FILE__) . '/../uploads/pages/' . $id;
 if (!file_exists($dir)) {
     $dirCreate = mkdir($dir);
     for ($i = 1; $i <= $details['Pages']; $i++) {
         $fpdi = new FPDI();
         $fpdi->setSourceFile($filepath);
         $tpl = $fpdi->importPage($i);
         $size = $fpdi->getTemplateSize($tpl);
         $orientation = $size['h'] > $size['w'] ? 'P' : 'L';
         $fpdi->AddPage($orientation);
         $fpdi->useTemplate($tpl, null, null, $size['w'], $size['h'], true);
         try {
             $filename = dirname(__FILE__) . '/../uploads/pages/' . $id . '/' . $i;
             $fpdi->Output($filename . '.pdf', "F");
             $imagick = new Imagick();
             $imagick->readimage($filename . '.pdf');
             $imagick->setImageFormat('jpeg');
             $imagick->setCompressionQuality(20);
             $imagick->writeImage($filename . '.jpg');
             $imagick->clear();
             $imagick->destroy();
         } catch (Exception $e) {
             echo 'Caught exception: ', $e->getMessage(), "\n";
         }
     }
 }
 $jsonFile = dirname(__FILE__) . '/../uploads/' . $id . '.json';
 $genJSONurl = "http://{$_SERVER['HTTP_HOST']}/parser/public/getPDFjson/{$id}";
 if (!file_exists($jsonFile)) {
     file_put_contents($jsonFile, file_get_contents($genJSONurl));
 }
Exemple #12
0
imagefilledpolygon($im, $team1bar, 4, $teamcolor);
imagefilledpolygon($im, $team2bar, 4, $team2color);
$frame = imagecreatefrompng('assets/scoreframe.png');
imagecopy($im, $frame, 0, 0, 0, 0, 640, 480);
$logo1 = imagecreatefrompng('teamlogos\\' . $teamrow["logo"]);
imagecopyresampled($im, $logo1, 67, 262, 0, 0, 75, 75, 100, 100);
$logo2 = imagecreatefrompng('teamlogos\\' . $team2row["logo"]);
imagecopyresampled($im, $logo2, 67, 342, 0, 0, 75, 75, 100, 100);
imagefttext($im, 30, 0, 183, 317, $black, $font, $row["content"]);
imagefttext($im, 30, 0, 180, 314, $white, $font, $row["content"]);
imagefttext($im, 30, 0, 183, 397, $black, $font, $row["col2"]);
imagefttext($im, 30, 0, 180, 394, $white, $font, $row["col2"]);
$dummy = imagefttext($im, 60, 0, 700, 328, $black, $fontb, $row["col1"]);
imagefttext($im, 60, 0, 532 - ($dummy[2] - $dummy[0]) / 2, 331, $black, $fontb, $row["col1"]);
imagefttext($im, 60, 0, 529 - ($dummy[2] - $dummy[0]) / 2, 328, $white, $fontb, $row["col1"]);
$dummy = imagefttext($im, 60, 0, 700, 328, $black, $fontb, $row["col3"]);
imagefttext($im, 60, 0, 532 - ($dummy[2] - $dummy[0]) / 2, 411, $black, $fontb, $row["col3"]);
imagefttext($im, 60, 0, 529 - ($dummy[2] - $dummy[0]) / 2, 408, $white, $fontb, $row["col3"]);
$dummy = imagefttext($im, 18, 0, 700, 328, $black, $fontb, $row["title"]);
imagefttext($im, 18, 0, 313 - ($dummy[2] - $dummy[0]) / 2, 447, $black, $font, $row["title"]);
imagefttext($im, 18, 0, 310 - ($dummy[2] - $dummy[0]) / 2, 444, $white, $font, $row["title"]);
header('Content-Type: image/png');
imagealphablending($im, false);
imagesavealpha($im, true);
imagepng($im, "pngout/" . $row["filename"] . '.png');
imagepng($im);
imagedestroy($im);
$magick = new Imagick();
$magick->readimage("pngout/" . $row["filename"] . '.png');
$magick->setImageFormat("tga");
$magick->writeImage("out/" . $row["filename"] . '.tga');
Exemple #13
0
 /**
  * 
  * 获取图片信息
  * @param unknown_type $img
  */
 public function getImageInfo($img)
 {
     $image = new Imagick($img);
     $handle = $image->readimage($img);
     if (!$handle) {
         return false;
     }
     $width = $image->getimagewidth();
     $height = $image->getimageheight();
     $mime = $image->getimagemimetype();
     $type = $image->getimageformat();
     $size = $image->getimagesize();
     $resolution = $image->getimageresolution();
     $unit = $image->getimageunits();
     $info = array('width' => $width, 'height' => $height, 'mime' => $mime, 'type' => $type, 'size' => $size, 'resolution' => $resolution, 'unit' => $unit);
     $image->destroy();
     return $info;
 }
Exemple #14
0
 /**
  * Load a PDF for use on the printer
  *
  * @param string $pdfFile The file to load
  * @param string $pageWidth The width, in pixels, of the printer's output. The first page of the PDF will be scaled to approximately fit in this area.
  * @param array $range array indicating the first and last page (starting from 0) to load. If not set, the entire document is loaded.
  * @throws Exception Where Imagick is not loaded, or where a missing file or invalid page number is requested.
  * @return multitype:EscposImage Array of images, retrieved from the PDF file.
  */
 public static function loadPdf($pdfFile, $pageWidth = 550)
 {
     if (!extension_loaded('imagick')) {
         throw new Exception(__FUNCTION__ . " requires imagick extension.");
     }
     /*
      * Load first page at very low density (resolution), to figure out what
      * density to use to achieve $pageWidth
      */
     try {
         $image = new \Imagick();
         $testRes = 2;
         // Test resolution
         $image->setresolution($testRes, $testRes);
         /* Load document just to measure geometry */
         $image->readimage($pdfFile);
         $geo = $image->getimagegeometry();
         $image->destroy();
         $width = $geo['width'];
         $newRes = $pageWidth / $width * $testRes;
         /* Load entire document in */
         $image->setresolution($newRes, $newRes);
         $image->readImage($pdfFile);
         $pages = $image->getNumberImages();
         /* Convert images to Escpos objects */
         $ret = array();
         for ($i = 0; $i < $pages; $i++) {
             $image->setIteratorIndex($i);
             $ep = new EscposImage();
             $ep->readImageFromImagick($image);
             $ret[] = $ep;
         }
         return $ret;
     } catch (\ImagickException $e) {
         // Wrap in normal exception, so that classes which call this do not themselves require imagick as a dependency.
         throw new Exception($e);
     }
 }
Exemple #15
0
 /**
  * Converts this attachment into a JPEG if ir is an image.
  */
 public function convertToPNG()
 {
     if ($this->getAttachmentType() != self::ATTACHMENT_TYPE_IMAGE) {
         return;
     }
     $imagick = new Imagick();
     $imagick->readimage(self::getStoragePath($this->getAttachmentId()));
     $imagick->setimageformat('png');
     $imagick->writeimage();
 }
Exemple #16
0
    $result = imagefttext($im, $labelsize, 0, $result[2] + 15, $labelheight, $white, $arial, "Goals");
    $dummy = imagefttext($im, $statssize, 0, 700, $statsheight, $white, $arial, $row["g"]);
    imagefttext($im, $statssize, 0, ($result[2] - $result[0]) / 2 - ($dummy[2] - $dummy[0]) / 2 + $result[0], $statsheight, $white, $arial, $row["g"]);
    $result = imagefttext($im, $labelsize, 0, $result[2] + 15, $labelheight, $white, $arial, "Assists");
    $dummy = imagefttext($im, $statssize, 0, 700, $statsheight, $white, $arial, $row["a"]);
    imagefttext($im, $statssize, 0, ($result[2] - $result[0]) / 2 - ($dummy[2] - $dummy[0]) / 2 + $result[0], $statsheight, $white, $arial, $row["a"]);
    $result = imagefttext($im, $labelsize, 0, $result[2] + 15, $labelheight, $white, $arial, "Points");
    $dummy = imagefttext($im, $statssize, 0, 700, $statsheight, $white, $arial, $row["pts"]);
    imagefttext($im, $statssize, 0, ($result[2] - $result[0]) / 2 - ($dummy[2] - $dummy[0]) / 2 + $result[0], $statsheight, $white, $arial, $row["pts"]);
    if ($row["team"] != "career") {
        if ($teamrow["womens"] == "2" || $teamrow["womens"] == "3") {
            $result = imagefttext($im, $labelsize, 0, $result[2] + 15, $labelheight, $white, $arial, "Shots");
        } else {
            $result = imagefttext($im, $labelsize, 0, $result[2] + 15, $labelheight, $white, $arial, "PIM");
        }
        $dummy = imagefttext($im, $statssize, 0, 700, $statsheight, $white, $arial, $row["pen"]);
        imagefttext($im, $statssize, 0, ($result[2] - $result[0]) / 2 - ($dummy[2] - $dummy[0]) / 2 + $result[0], $statsheight, $white, $arial, $row["pen"]);
    }
}
$logo = imagecreatefrompng('teamlogos\\' . $row["team"] . '.png');
imagecopyresampled($im, $logo, 550, 0, 0, 0, 40, 40, 100, 100);
header('Content-Type: image/png');
imagealphablending($im, false);
imagesavealpha($im, true);
imagepng($im, "pngout/" . $row["num"] . $row["first"] . $row["last"] . '.png');
imagepng($im);
imagedestroy($im);
$magick = new Imagick();
$magick->readimage("pngout/" . $row["num"] . $row["first"] . $row["last"] . '.png');
$magick->setImageFormat("tga");
$magick->writeImage("out/" . $row["team"] . $row["num"] . $row["first"] . $row["last"] . '.tga');
Exemple #17
0
 public function test()
 {
     //        $rgb_arr = sscanf('rgb(243, 243, 243)', "rgb(%d, %d, %d)");
     //        print_r($this->rgbToCmyk($rgb_arr[0], $rgb_arr[1], $rgb_arr[2]));
     //        exit();
     //
     $img = new Imagick('test.jpg');
     $img->resizeimage(1076, 720, Imagick::FILTER_LANCZOS, 1);
     $img->setresolution(300, 300);
     $img->setimageformat('pdf');
     $img->writeimage('test.pdf');
     include_once APPPATH . 'libraries/tcpdf/tcpdf.php';
     include_once APPPATH . 'libraries/tcpdf/fpdi.php';
     // создаём лист
     $pdf = new FPDI('L', 'mm', array(91, 61), true, 'UTF-8', false);
     $pdf->AddPage('L');
     // загрузим ранее сохранённый шаблон
     $pdf->setSourceFile('test.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);
     $pdf->Image('qwe.png', 30, 30, 20, '', '', '', '', false, 300);
     $pdf->SetTextColor(0, 0, 0, 100);
     $pdf->SetFont('helvetica', 'BI', 10, '', 'false');
     $pdf->Text(12, 9, 'Black CMYK');
     $pdf->Output($_SERVER['DOCUMENT_ROOT'] . '/uploads/fynal.pdf', 'F');
     $im = new Imagick();
     $im->setResolution(300, 300);
     $im->readimage('uploads/fynal.pdf[0]');
     $im->setImageFormat('jpeg');
     $im->resizeimage(538, 360, Imagick::FILTER_LANCZOS, 1);
     $im->writeImage('uploads/fynal.jpg');
     $im->clear();
     $im->destroy();
     //        include_once APPPATH . 'libraries/drawer.php';
     //
     //        $drawer = new Drawer();
     //        $drawer->init();
     //        $drawer->setLayout();
     //        $drawer->setBackground('test.jpg');
     //        $drawer->drawImage('test.jpg', 10, 10, 30);
     //        $drawer->drawText('Maxim', 10, 10, 'TimesNewRoman', 20, 'rgb(77, 77, 77)');
     //        $drawer->savePdf($_SERVER['DOCUMENT_ROOT'] . '/1.pdf');
     //        $drawer->makePreview($_SERVER['DOCUMENT_ROOT'] . '/1.pdf', $_SERVER['DOCUMENT_ROOT'] . '/1.jpg');
 }
Exemple #18
0
 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';
 }
Exemple #19
0
 public function importImage()
 {
     $db = ConnectionManager::getDataSource('default');
     $this->mysqli = new mysqli($db->config['host'], $db->config['login'], $db->config['password'], $db->config['database']);
     $this->dbQuery('SET NAMES utf8mb4;');
     $fields = array('許可證字號', '中文品名', '英文品名', '形狀', '特殊劑型', '顏色', '特殊氣味', '刻痕', '外觀尺寸', '標註一', '標註二', '外觀圖檔連結', '-');
     $imagePath = TMP . '/drugs/images';
     if (!file_exists($imagePath)) {
         mkdir($imagePath, 0777, true);
     }
     $fh = fopen($this->dataPath . '/dataset/42.csv', 'r');
     $dbKeys = array();
     if (file_exists(__DIR__ . '/data/keys/licenses.csv')) {
         $dbKeysFh = fopen(__DIR__ . '/data/keys/licenses.csv', 'r');
         while ($line = fgetcsv($dbKeysFh, 1024)) {
             $dbKeys[$line[0]] = $line[1];
         }
         fclose($dbKeysFh);
     }
     /*
     * Array
      (
      [0] => 許可證字號
      [1] => 中文品名
      [2] => 英文品名
      [3] => 形狀 shape
      [4] => 特殊劑型 s_type
      [5] => 顏色 color
      [6] => 特殊氣味 odor
      [7] => 刻痕 abrasion
      [8] => 外觀尺寸 size
      [9] => 標註一 note_1
      [10] => 標註二 note_2
      [11] => 外觀圖檔連結 image
      [12] => -
      )
     */
     $wLength = strlen(WWW_ROOT);
     $imagick = new Imagick();
     while ($line = fgetcsv($fh, 2048, "\t")) {
         $dataFound = $licenseCode = false;
         for ($k = 3; $k <= 11; $k++) {
             if (!empty($line[$k])) {
                 $dataFound = true;
             }
         }
         if ($dataFound) {
             $licenseCode = $this->getLicenseCode($line[0]);
         }
         if (false === $licenseCode || !isset($dbKeys[$licenseCode])) {
             continue;
         } else {
             if (!empty($line[11])) {
                 $imgs = explode(';;', $line[11]);
                 $line[11] = $imgs[0];
                 $targetFile = WWW_ROOT . 'img/drugs/' . substr($dbKeys[$licenseCode], 0, 8) . '/' . $dbKeys[$licenseCode] . '.jpg';
                 if (!file_exists($targetFile)) {
                     $imageFile = $imagePath . '/' . $dbKeys[$licenseCode];
                     file_put_contents($imageFile, file_get_contents($line[11]));
                     $line[11] = '';
                     if (file_exists($imageFile)) {
                         if (filesize($imageFile) > 0) {
                             if (in_array(mime_content_type($imageFile), array('application/vnd.ms-powerpoint', 'application/msword', 'text/html'))) {
                                 unlink($imageFile);
                             } else {
                                 $targetFile = WWW_ROOT . 'img/drugs/' . substr($dbKeys[$licenseCode], 0, 8);
                                 if (!file_exists($targetFile)) {
                                     mkdir($targetFile, 0777, true);
                                 }
                                 $targetFile .= '/' . $dbKeys[$licenseCode] . '.jpg';
                                 $line[11] = substr($targetFile, $wLength);
                                 if (!file_exists($targetFile)) {
                                     $imagick->readimage($imageFile);
                                     $imagick->thumbnailimage(512, 512, true, true);
                                     $imagick->writeImage($targetFile);
                                     $imagick->clear();
                                 }
                             }
                         }
                         //unlink($imageFile);
                     }
                 } else {
                     $line[11] = substr($targetFile, $wLength);
                 }
             }
             $this->dbQuery("UPDATE licenses SET shape = '{$line[3]}', s_type = '{$line[4]}', color = '{$line[5]}', odor = '{$line[6]}', abrasion = '{$line[7]}', size = '{$line[8]}', note_1 = '{$line[9]}', note_2 = '{$line[10]}', image = '{$line[11]}' WHERE id = '{$dbKeys[$licenseCode]}'");
         }
     }
 }
Exemple #20
0
 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();
 }
Exemple #21
0
 public function writeWatermarkIm($opacity = 50, $marginH = 0, $marginV = 0, $positionWatermarkLeftRight = 'c', $positionWatermarkTopBottom = 'c')
 {
     //add Watermark
     list($imageCreateFunc, $imageSaveFunc) = $this->_watermark->_getFunctionNames();
     $watermarkImage = $imageCreateFunc($this->_watermark->_getImage());
     //get base image
     list($imageCreateFunc, $imageSaveFunc) = $this->_getFunctionNames();
     $baseImage = @$imageCreateFunc($this->_image);
     if (!$baseImage) {
         return false;
     }
     //Calculate margins
     if ($positionWatermarkLeftRight == 'r') {
         $marginH = imagesx($baseImage) - imagesx($watermarkImage) - $marginH;
     }
     if ($positionWatermarkLeftRight == 'c') {
         $marginH = imagesx($baseImage) / 2 - imagesx($watermarkImage) / 2 - $marginH;
     }
     if ($positionWatermarkTopBottom == 'b') {
         $marginV = imagesy($baseImage) - imagesy($watermarkImage) - $marginV;
     }
     if ($positionWatermarkTopBottom == 'c') {
         $marginV = imagesy($baseImage) / 2 - imagesy($watermarkImage) / 2 - $marginV;
     }
     $image = new Imagick($this->_image);
     $image->coalesceimages();
     $watermark = new Imagick();
     $watermark->readimage($this->_watermark->_getImage());
     $watermark->evaluateImage(Imagick::EVALUATE_DIVIDE, 100 / $opacity, Imagick::CHANNEL_ALPHA);
     if ($imageSaveFunc == 'ImageGIF') {
         if (XenForo_Application::getOptions()->xengalleryWatermarkAnimated) {
             try {
                 foreach ($image as $frame) {
                     $frame->compositeImage($watermark, imagick::COMPOSITE_OVER, $marginH, $marginV);
                 }
                 if (!$image->writeimages($this->tmpFile, true)) {
                     throw new Exception('Cannot save file ' . $this->tmpFile);
                 }
             } catch (Exception $e) {
                 return false;
             }
         } else {
             return false;
         }
     } else {
         $image->compositeImage($watermark, imagick::COMPOSITE_OVER, $marginH, $marginV);
         if (!$image->writeimage($this->tmpFile)) {
             throw new Exception('Cannot save file ' . $this->tmpFile);
         }
     }
     //Set new main image
     $this->_setNewMainImage($this->tmpFile);
     $image->destroy();
     $watermark->destroy();
     return true;
 }