Generating thumbnails for a image record

@param $id
@throws \Exception
187798
private function generateGlobalThumb($id)
    {
        $resource = HCResources::find($id);

        if( ! file_exists(storage_path('app/') . $resource->path) )
            return;

        if( strpos($resource->mime_type, 'image') === false || strpos($resource->mime_type, 'svg') !== false )
            return;

        if( ! $resource )
            throw new \Exception('Resource not found: ' . $id);

        $thumbRules = HCThumbs::where('global', 1)->get();
        $dest = implode('/', str_split(str_pad($resource->count, 9, '0', STR_PAD_LEFT), 3)) . '/';

        foreach ( $thumbRules as $rule ) {
            $destination = generateResourcePublicLocation($dest, $rule->width, $rule->height, $rule->fit) . $resource->extension;
            createImage(storage_path('app/') . $resource->path, $destination, $rule->width, $rule->height, $rule->fit);
        }
    }
742363
public function deleteRow(int $id) : void
    {
        $this->crudEnabled();

        // Generate the values
        $table_name = static::$table_name;
        $id_column = static::$id_column;

        $sql = "DELETE FROM {$table_name} WHERE {$id_column} = :key";
        $this->dbc->query($sql, ['params' => [':key' => $id]]);
    }
659881
def thumbnail(self, id):
        
        res = self._raw_api_request('thumb', data={'i': id})
        if not res:
            raise PuushError("Getting thumbnail failed.")
        return res
234057
public function loadByMageOrderId($id)
    {
        $order = $this->_getResource()->getByOrderId($id);
        if (!empty($order)) {
            $this->setData($order);
        }

        return $this;
    }
1374139
public function format($id, $recordObj)
    {
        if (!isset($recordObj->metadata)) {
            throw new \Exception("Unexpected missing record metadata.");
        }

        $raw = trim($recordObj->metadata->asXML());

        // Extract the actual metadata from inside the <metadata></metadata> tags;
        // there is probably a cleaner way to do this, but this simple method avoids
        // the complexity of dealing with namespaces in SimpleXML.
        //
        // We should also apply global search and replace at this time, if
        // applicable.
        $record = $this->performGlobalReplace(
            preg_replace('/(^<metadata[^\>]*>)|(<\/metadata>$)/m', '', $raw)
        );

        // Collect attributes (for proper namespace resolution):
        $metadataAttributes = $this->extractMetadataAttributes($raw, $record);

        // If we are supposed to inject any values, do so now inside the first
        // tag of the file:
        $insert = $this->getIdAdditions($id)
            . $this->getHeaderAdditions($recordObj->header);
        $xml = !empty($insert)
            ? preg_replace('/>/', '>' . $insert, $record, 1) : $record;

        // Build the final record:
        return trim(
            $this->fixNamespaces(
                $xml, $recordObj->getDocNamespaces(), $metadataAttributes
            )
        );
    }
923588
public function getById($id)
    {
        $image = $this->adapter->get(sprintf('%s/images/%d', $this->endpoint, $id));

        $image = json_decode($image);

        return new ImageEntity($image->image);
    }
819246
protected function setIds($id)
    {
        if ($id) {
            $this->props = $this->mergeProps(array(
                $this->props,
                array(
                    'attribsContainer' => array(
                        'id' => $id.'_container',
                    ),
                    'attribs' => array(
                        'id' => $id,
                    ),
                    'attribsLabel' => array(
                        'for' => $id,
                    ),
                    'attribsHelpBlock' => array(
                        'id' => $id.'_help_block',
                    ),
                ),
            ));
        }
    }
1260448
public function handlePreviousImage(int $id): void
	{
		if ($this->request->isAjax()) {
			$row = $this->getStorage()->getPrevious($id);
			if ($row) {
				$this->template->viewImage = $row;
				$this->redrawControl('image');
			} else {
				throw new AbortException;
			}
		} else {
			throw new AbortException;
		}
	}
191651
public function AnimePictures(int $id): array
    {
        return $this->myanimelist->getAnimePictures(
            new Request\Anime\AnimePicturesRequest($id)
        );
    }
338360
private function getImage($id)
    {
        $image = $this->getImageRepository()->find($id);

        if (empty($image)) {
            throw $this->createNotFoundException(sprintf('Unable to find image by ID "%d".', $id));
        }

        return $image;
    }
1003402
public function strokeFromCache($ID)
    {
        /* Get the raw picture from the cache */
        $Picture = $this->getFromCache($ID);

        /* Do we have a hit? */
        if ($Picture == null) {
            return false;
        }

        header('Content-type: image/png');
        echo $Picture;

        return true;
    }
508790
public function setDatatableId($id)
    {
        if (!array_key_exists($id, self::$instances)) {
            self::$instances[$id] = $this;
        } else {
            throw new \Exception('Identifer already exists');
        }

        return $this;
    }
139091
protected function generateImage($id, $word)
    {
        $font = $this->getFont();

        if (empty($font)) {
            throw new Exception\NoFontProvidedException('Image CAPTCHA requires font');
        }

        $w     = $this->getWidth();
        $h     = $this->getHeight();
        $fsize = $this->getFontSize();

        $img_file   = $this->getImgDir() . $id . $this->getSuffix();

        if (empty($this->startImage)) {
            $img = new Imagick();
            $img->newImage($w, $h, new ImagickPixel('#FFFFFF'), 'png');
        } else {
            $img = new Imagick($this->startImage);
            $w = $img->getImageWidth();
            $h = $img->getImageHeight();
        }

        $text = new ImagickDraw();
        $text->setFillColor('#000000');
        $text->setFont($font);
        $text->setFontSize(empty($fsize) ? $h - 10 : $fsize);
        $text->setGravity(Imagick::GRAVITY_CENTER);
        $text->annotation(0, 0, $word);
        $img->drawImage($text);

        // generate noise
        $noise = new ImagickDraw();
        $noise->setFilLColor('#000000');
        for ($i=0; $i<$this->dotNoiseLevel; $i++) {
            $x = mt_rand(0, $w);
            $y = mt_rand(0, $h);
            $noise->circle($x, $y, $x+mt_rand(0.3, 1.7), $y+mt_rand(0.3, 1.7));
        }
        for ($i=0; $i<$this->lineNoiseLevel; $i++) {
            $noise->line(mt_rand(0, $w), mt_rand(0, $h), mt_rand(0, $w), mt_rand(0, $h));
        }

        $img->waveImage(5, mt_rand(60, 100));
        $img->scaleimage($w, $h);
        $img->drawImage($noise);
        $img->swirlImage(mt_rand(10, 30));

        file_put_contents($img_file, $img);
        unset($img);
    }
130824
public function enableAction($id)
    {
        $image = $this->getImage($id);

        if ($image->isEnabled()) {
            throw $this->createNotFoundException(sprintf('Image with ID "%d" already enabled.', $id));
        }

        $image->setEnabled(true);

        $this->getDoctrine()->getManager()->flush();

        return new Response();
    }
648820
private function adminImageToggle($id)
    {
        $table = ORM::getTable($this, 'Image');
        /* @var Gallery_Entity_Image $image */
        $image = $table->find($id);
        $image->active = ! $image->active;
        $table->update($image);

        HTTP::goback();
    }
680392
public function runSingleApiCallAction($id)
        {


            $sLico = SystemSettings::get("lico");
            $iLvdc = SystemSettings::get("lvdc");

            if ($iLvdc < strtotime("-7 days")) {
                $aRemoteApps = RemoteAppQuery::create()->filterByWebsiteHash(null, \Criteria::ISNOTNULL);
                $lico        = $sLico . "/api/lvdc/" . base64_encode($this->_getSiteURL()) . "/" . $aRemoteApps->count();
                try {
                    $res = @file_get_contents($lico);
                    if ($res === false) {
                        throw new \Exception($this->get("translator")->trans("license.update.failed_lico"));
                    }
                    $oResult = json_decode($res);

                    if ($oResult->valid !== true) {
                        $aResponse = array(
                            "error"   => true,
                            "message" => $oResult->message
                        );
                    } else {
                        SystemSettings::set("lvdc", time());
                    }

                } catch (\Exception $e) {
                    $aResponse = array(
                        "error"   => true,
                        "message" => $e->getMessage()
                    );
                }
            }


            try {

                if (!isset($aResponse)) {
                    $command = new ApiCommand();
                    $command->setContainer($this->container);
                    $input  = new ArgvInput(array(
                                                'control:remote:cron',
                                                '--app=' . $id,
                                                '--force'
                                            ));


                    $output = new BufferedOutput();
                    // Run the command
                    $retval     = $command->run($input, $output);
                    $oRemoteApp = RemoteAppQuery::create()->findOneById($id);
                    $sJsonData  = $this->renderView('SlashworksAppBundle:RemoteApp:data.json.twig', array('entities' => array($oRemoteApp)));
                    $aData      = json_decode($sJsonData, true);

                    $sReturn = $output->fetch();
                    $aReturn = json_decode($sReturn, true);

                    if($aReturn !== false){
                        if(is_array($aReturn)){
                            if($aReturn['status'] === false) {
                                $this->get('logger')->error($aReturn['message'], array("Method" => __METHOD__, "RemoteApp" => $oRemoteApp->getName(), "RemoteURL" => $oRemoteApp->getFullApiUrl()));
                                $aResponse = $aReturn;
                            }elseif($aReturn['status'] === true) {
                                $this->get('logger')->info("Api-Call successful", array("Method" => __METHOD__, "RemoteApp" => $oRemoteApp->getName()));
                                $aResponse = $aData;
                            } else {
                                $this->get('logger')->error("Unknown error in ".__FILE__." on line ".__LINE__, array("Method" => __METHOD__, "RemoteApp" => $oRemoteApp->getName(), "RemoteURL" => $oRemoteApp->getFullApiUrl()));
                                $aResponse = array("error" => true);
                            }
                        }
                    }else {

                        if (!$retval) {
                            $this->get('logger')->info("Api-Call successful", array("Method" => __METHOD__, "RemoteApp" => $oRemoteApp->getName()));
                            $aResponse = $aData;
                        } else {
                            $this->get('logger')->error("Unknown error in ".__FILE__." on line ".__LINE__, array("Method" => __METHOD__, "RemoteApp" => $oRemoteApp->getName(), "RemoteURL" => $oRemoteApp->getFullApiUrl()));
                            $aResponse = array("error" => true);
                        }
                    }
                }
            } catch (\Exception $e) {
                $this->get('logger')->error($e->getMessage());
                $aResponse = array(
                    "error"   => true,
                    "message" => $e->getMessage()
                );
            }

            $response = new Response(json_encode($aResponse));
            $response->headers->set('Content-Type', 'application/json');

            return $response;
        }
406865
public function picture($id, $name, $email, $thumbnail = true)
	{
		$processor = new Processor();

		$size = $this->pictureSize;
		$file = $this->pictureName;

		if ($thumbnail)
		{
			$size = $this->thumbnailSize;
			$file = $this->thumbnailName;
		}

		$dir  = $this->path . DIRECTORY_SEPARATOR . Str::pad($id, 5) . DIRECTORY_SEPARATOR;
		$path = $dir . $file;

		if (file_exists($path))
		{
			return with(new Moderator($path, 'public'))->getUrl();
		}

		$image = $processor->getImageData($email, $size, $this->color);

		if (!is_dir($dir))
		{
			@mkdir($dir, 0755, true);
		}
		@file_put_contents($path, $image);

		if (!file_exists($path))
		{
			return sprintf('data:image/png;base64,%s', base64_encode($image));
		}

		return with(new Moderator($path, 'public'))->getUrl();
	}