Beispiel #1
0
/**
 * Процесс строит скрипты для вставки ячеек в БД
 * 
 * @param array $argv
 */
function executeProcess(array $argv)
{
    $DM = DirManager::inst(array(__DIR__, 'output'));
    $customNum = $argv[1];
    dolog('Processing mosaic demo, custom num={}', $customNum);
    /* @var $dir DirItem */
    foreach ($DM->getDirContent(null, DirItemFilter::DIRS) as $dir) {
        if (is_inumeric($customNum) && $customNum != $dir->getName()) {
            continue;
            //----
        }
        $imgDM = DirManager::inst($dir->getAbsPath());
        $imgDI = end($imgDM->getDirContent(null, DirItemFilter::IMAGES));
        $map = $imgDM->getDirItem(null, 'map', 'txt')->getFileAsProps();
        $demoDM = DirManager::inst($imgDM->absDirPath(), 'demo');
        $demoDM->clearDir();
        dolog("Building map for: [{}].", $imgDI->getRelPath());
        //CELLS BINDING
        $dim = $imgDM->getDirItem(null, 'settings', 'txt')->getFileAsProps();
        $dim = $dim['dim'];
        $dim = explode('x', $dim);
        $cw = 1 * $dim[0];
        $ch = 1 * $dim[1];
        $sourceImg = SimpleImage::inst()->load($imgDI);
        $w = $sourceImg->getWidth();
        $h = $sourceImg->getHeight();
        $destImg = SimpleImage::inst()->create($w, $h, MosaicImage::BG_COLOR);
        dolog("Img size: [{$w} x {$h}].");
        check_condition($w > 0 && !($w % $cw), 'Bad width');
        check_condition($h > 0 && !($h % $ch), 'Bad height');
        $totalCells = count($map);
        $lengtn = strlen("{$totalCells}");
        //dolog("Cells cnt: [$xcells x $ycells], total: $totalCells.");
        //СТРОИМ КАРТИНКИ
        $secundomer = Secundomer::startedInst();
        //$encoder = new PsGifEncoder();
        for ($cellCnt = 0; $cellCnt <= $totalCells; $cellCnt++) {
            $name = pad_zero_left($cellCnt, $lengtn);
            $copyTo = $demoDM->absFilePath(null, $name, 'jpg');
            if ($cellCnt > 0) {
                $cellParams = $map[$cellCnt];
                $cellParams = explode('x', $cellParams);
                $xCell = $cellParams[0];
                $yCell = $cellParams[1];
                $x = ($xCell - 1) * $cw;
                $y = ($yCell - 1) * $ch;
                $destImg->copyFromAnother($sourceImg, $x, $y, $x, $y, $cw, $ch);
            }
            $destImg->save($copyTo);
            dolog("[{$totalCells}] {$copyTo}");
        }
        //$encoder->saveToFile($demoDM->absFilePath(null, 'animation'));
        $secundomer->stop();
        dolog('Execution time: ' . $secundomer->getTotalTime());
    }
}
Beispiel #2
0
 public function createSmallCovers($forceRecr = false)
 {
     /* @var $ex GymEx */
     foreach ($this->getExercises() as $ex) {
         $curImg = $this->absCoverPath($ex->getId());
         if (!PsImg::isImg($curImg)) {
             continue;
         }
         $imgNew = $this->absCoverPathSmall($ex->getId());
         if (!PsImg::isImg($imgNew) || $forceRecr) {
             SimpleImage::inst()->load($curImg)->resizeSmart($this->dim, $this->dim)->save($imgNew)->close();
         }
     }
 }
Beispiel #3
0
 /**
  * Анимация
  */
 public function getAnimation()
 {
     if (isset($this->animation)) {
         return $this->animation;
     }
     check_condition($this->IMAGES, 'No images for gif');
     PsLibs::inst()->GifEncoder();
     $frames = array();
     $framed = array();
     foreach ($this->IMAGES as $path => $delay) {
         ob_start();
         SimpleImage::inst()->load($path)->output(IMAGETYPE_GIF)->close();
         $frames[] = ob_get_contents();
         $framed[] = $delay;
         // Delay in the animation.
         ob_end_clean();
     }
     // Generate the animated gif and output to screen.
     $gif = new GIFEncoder($frames, $framed, 0, 2, 0, 0, 0, 'bin');
     $this->animation = $gif->GetAnimation();
     return $this->animation;
 }
Beispiel #4
0
/**
 * Конвертирует картинки в .png
 * 
 * @param array $argv
 */
function executeProcess(array $argv)
{
    $SRC_DIR = 'source';
    $OUT_DIR = 'output';
    $dm = DirManager::inst(__DIR__);
    //Создадим $SRC_DIR
    $dm->makePath($SRC_DIR);
    //Перенесём все картинки из корня в $SRC_DIR
    $items = $dm->getDirContent(null, DirItemFilter::IMAGES);
    /* @var $img DirItem */
    foreach ($items as $img) {
        $img->copyTo($dm->absFilePath($SRC_DIR, $img->getName()))->remove();
    }
    //Очистим $OUT_DIR
    $dm->clearDir($OUT_DIR)->makePath($OUT_DIR);
    //Список картинок
    $items = $dm->getDirContent($SRC_DIR, DirItemFilter::IMAGES);
    /* @var $img DirItem */
    foreach ($items as $img) {
        SimpleImage::inst()->load($img)->resizeSmart(36, 36)->save($dm->absFilePath($OUT_DIR, $img->getNameNoExt(), 'png'), IMAGETYPE_PNG)->close();
    }
}
Beispiel #5
0
 /**
  * Копирует ячейки из картинки-источника в картинку-мозайку.
  * 
  * @param array $INFO - информация о картинке
  * @param array $cells - ячейки из БД, которые будут скопированы
  * @param type $userId - код пользователя, к которому ячейки будут привязаны
  */
 private function copyCells(array $cells, $userId = null)
 {
     //Проверим, есть ли сейчас "чистая" картинка, на которую мы будем копировать ячейки
     if (!$this->diDst()->isImg()) {
         SimpleImage::inst()->create($this->width, $this->height, self::BG_COLOR)->save($this->diDst())->close();
     }
     if (empty($cells)) {
         return;
         //---
     }
     if ($this->LOGGER->isEnabled()) {
         $this->LOGGER->info('Copy cells of image ' . $this->id . ', user for bind: ' . var_export($userId, true));
         $this->LOGGER->info('Not processed cells: ' . print_r($cells, true));
     }
     PsUtil::startUnlimitedMode();
     $this->PROFILER->start('Copy cells of img ' . $this->id);
     //1. Разберёмся с ячейками - привяжем к пользователю те их них, которые никому не принадлежат
     foreach ($cells as $cell) {
         $n_part = 1 * $cell['n_part'];
         $owned = !!$cell['owned'];
         //Ячейка должна кому-то принадлежать, либо быть привязана к переданному пользователю
         check_condition($owned || is_numeric($userId), "Ячейка {$this->id}.{$n_part} никому не принадлежит.");
         if (!$owned) {
             //Если ячейка уже привязана к пользователю, то не будем лишний раз дёргать базу
             $this->LOGGER->info('{}. Cell binded to user {}', $n_part, $userId);
             $this->BEAN->markAsOwned($userId, $this->id, $n_part);
         }
     }
     //2. Копируем ячейки, предварительно объединив их
     $srcImg = SimpleImage::inst()->load($this->diSrc());
     $dstImg = SimpleImage::inst()->load($this->diDst());
     $unioned = MosaicImageCellsCompositor::union($cells, $this->cellWidth, $this->cellHeight, false);
     foreach ($unioned as $cell) {
         $x1 = $cell[0];
         $y1 = $cell[1];
         $x2 = $cell[2];
         $y2 = $cell[3];
         $w = $x2 - $x1;
         $h = $y2 - $y1;
         $dstImg->copyFromAnother($srcImg, $x1, $y1, $x1, $y1, $w, $h)->save();
         $this->LOGGER->info('Copied rectangle: {}x{}-{}x{}', $x1, $y1, $x2, $y2);
     }
     $srcImg->close();
     $dstImg->close();
     $this->PROFILER->stop();
 }
Beispiel #6
0
}
$items = $dm->getDirContent($SRC_DIR, DirItemFilter::IMAGES);
if (isEmpty($items)) {
    return;
    //---
}
//Массив для сохранения информации о картинках
$images = array();
//Создадим $OUT_DIR
$dm->makePath($OUT_DIR);
$outputDir = $dm->absDirPath($OUT_DIR);
foreach ($items as $item) {
    $name = $item->getNameNoExt();
    $srcImg = SimpleImage::inst()->load($item);
    $w = $srcImg->getWidth();
    $h = $srcImg->getHeight();
    $outImg = SimpleImage::inst()->create($w, $h, null);
    for ($x = 0; $x < $w; $x++) {
        for ($y = 0; $y < $h; $y++) {
            $rgb = $srcImg->colorAt($x, $y);
            if ($rgb != 16777215 && $rgb != 255) {
                $outImg->copyFromAnother($srcImg, $x, $y, $x, $y, 1, 1);
            }
        }
    }
    $filename = file_path($outputDir, $name, 'png');
    $outImg->save($filename, IMAGETYPE_PNG)->close();
    $srcImg->close();
    $images[] = array('rel' => file_path($OUT_DIR, $name, 'png'), 'rels' => file_path($SRC_DIR, $item->getName()), 'name' => $name);
}
saveResult2Html('pngs.tpl', array('items' => $images), __DIR__);
Beispiel #7
0
 private function doCopy(DirItem $from, DirItem $to)
 {
     $from->assertIsImg();
     PsLock::lockMethod(__CLASS__, __FUNCTION__);
     try {
         //Очистим нагенерённое для той картинки, В КОТОРУЮ копируем
         $this->doClean($to);
         //Картинка не была пересоздана в другом потоке
         SimpleImage::inst()->load($from)->save($to, SYSTEM_IMG_TYPE)->close();
     } catch (Exception $ex) {
         PsLock::unlock();
         throw $ex;
     }
     PsLock::unlock();
 }
Beispiel #8
0
$dm->makePath($SRC_DIR);
//Перенесём все картинки из корня в $SRC_DIR
$items = $dm->getDirContent(null, DirItemFilter::IMAGES);
foreach ($items as $img) {
    copy($img->getAbsPath(), $dm->absFilePath($SRC_DIR, $img->getName()));
    $img->remove();
}
//Удалим из $SRC_DIR всё, кроме *.bat и *.php
$items = $dm->getDirContent(null, DirItemFilter::FILES);
foreach ($items as $file) {
    if (!$file->checkExtension(array('bat', 'php'))) {
        $file->remove();
    }
}
//Очистим $OUT_DIR
$items = $dm->getDirContent($OUT_DIR, DirItemFilter::IMAGES);
foreach ($items as $img) {
    $img->remove();
}
$items = $dm->getDirContent($SRC_DIR, DirItemFilter::IMAGES);
if (isEmpty($items)) {
    return;
    //---
}
//Создадим $OUT_DIR
$dm->makePath($OUT_DIR);
$outputDir = $dm->absDirPath($OUT_DIR);
foreach ($items as $item) {
    $name = $item->getNameNoExt();
    SimpleImage::inst()->load($item)->resizeSmart(36, 36)->save($dm->absFilePath($OUT_DIR, $name, 'png'), IMAGETYPE_PNG)->close();
}
Beispiel #9
0
 $imgDI = end($imgDM->getDirContent(null, DirItemFilter::IMAGES));
 $map = $imgDM->getDirItem(null, 'map', 'txt')->getFileAsProps();
 $demoDM = DirManager::inst($imgDM->absDirPath(), 'demo');
 $demoDM->clearDir();
 $imgAbs = $imgDI->getAbsPath();
 dolog("Building map for: [{$imgAbs}].");
 //CELLS BINDING
 $dim = $imgDM->getDirItem(null, 'settings', 'txt')->getFileAsProps();
 $dim = $dim['dim'];
 $dim = explode('x', $dim);
 $cw = 1 * $dim[0];
 $ch = 1 * $dim[1];
 $sourceImg = SimpleImage::inst()->load($imgAbs);
 $w = $sourceImg->getWidth();
 $h = $sourceImg->getHeight();
 $destImg = SimpleImage::inst()->create($w, $h, MosaicImage::BG_COLOR);
 dolog("Img size: [{$w} x {$h}].");
 check_condition($w > 0 && !($w % $cw), 'Bad width');
 check_condition($h > 0 && !($h % $ch), 'Bad height');
 $totalCells = count($map);
 $lengtn = strlen("{$totalCells}");
 //dolog("Cells cnt: [$xcells x $ycells], total: $totalCells.");
 //СТРОИМ КАРТИНКИ
 $generator = new MosaicCellsGenerator($totalCells);
 $secundomer = Secundomer::startedInst();
 //$encoder = new PsGifEncoder();
 for ($cellCnt = 0; $cellCnt <= $totalCells; $cellCnt++) {
     $name = pad_zero_left($cellCnt, $lengtn);
     $copyTo = $demoDM->absFilePath(null, $name, 'jpg');
     if ($cellCnt > 0) {
         $cellParams = $map[$cellCnt];