GdDriver::createFromSource

Create an image resource from source file.

@return void
357972
public function createFromSource()
    {
        /**
         * A work-around for some improperly formatted, but
         * usable JPEGs; known to be produced by Samsung
         * smartphones' front-facing cameras.
         *
         * @see    https://bugs.php.net/bug.php?id=72404
         */
        ini_set('gd.jpeg_ignore_warning', 1);

        $mime = $this->sourceImageFile->getMime();
        $mime = is_array($mime) ? $mime[ 0 ] : $mime;

        try {
            switch ($mime) {
                case 'image/jpg':
                case 'image/jpeg':
                    $this->sourceImageResource = imagecreatefromjpeg($this->sourceImageFile->getRealPath());
                    break;

                case 'image/gif':
                    $this->sourceImageResource = imagecreatefromgif($this->sourceImageFile->getRealPath());
                    break;

                case 'image/png':
                case 'image/x-png':
                    $this->sourceImageResource = imagecreatefrompng($this->sourceImageFile->getRealPath());
                    break;
            }

            // Convert pallete images to true color images
            imagepalettetotruecolor($this->sourceImageResource);
        } catch (\Exception $e) {

        }
    }
253475
public function source($src)
    {
        $this->source = $this->getImageInfo($src);

        $type              = $this->source['type'];
        $createFrom        = 'ImageCreateFrom' . $type;
        $this->sourceImage = $createFrom($src);

        return $this;
    }
261776
private function createDriver()
    {
        switch ($this->driver) {
            case 'imagick':
                if (!IMAGICK_EXTENSION) {
                    throw new NotSupportedException('ImageMagick module not available with this PHP installation.');
                }

                $class = Imagick\Driver::class;
                break;

            case 'gd':
                if (!GD_EXTENSION) {
                    throw new NotSupportedException('GD Library extension not available with this PHP installation.');
                }

                $class = Gd\Driver::class;
                break;

            default:
                if (IMAGICK_EXTENSION) {
                    $class = Imagick\Driver::class;
                } elseif (GD_EXTENSION) {
                    $class = Gd\Driver::class;
                } else {
                    throw new NotSupportedException('Unknown driver type.');
                }
        }

        return $this->instance = new $class;
    }
276806
function makeResource()
    {
        $resource = $this->resource;
        if ($this->id) $resource .= '/' . $this->id;
        return $resource;
    }
1098958
public function createImageResource($keepHandleAlive = false): ImageResource {
		return new ImageResource(IoUtils::imageCreateFromGif($this->filePath), $keepHandleAlive);
	}
819067
public function createResizedImage(Image $file, $targetWidth, $targetHeight, $cropped = false, $quality = 95, $force = false)
	{
		// validate params
		if ( ! $file instanceof Image) {
			throw new Exception\RuntimeException('Image entity expected');
		}
		if (($targetWidth <= 0) || ($targetHeight <= 0)) {
			throw new Exception\RuntimeException('Dimensions are invalid');
		}

		$sizeName = $this->getImageSizeName($targetWidth, $targetHeight, $cropped);

		if ( ! $this->fileExists($file)) {
			$this->container->getLogger()->warn("Image '{$file->getFileName()}' is missing in the filesystem, tried to resize to {$sizeName}");

			return $sizeName;
		}

		$size = $file->getImageSize($sizeName);

		if (($size->getTargetHeight() == $targetHeight)
				&& ($size->getTargetWidth() == $targetWidth)
				&& ($size->getQuality() == $quality)
				&& ($size->getCropMode() == $cropped)
				&& empty($force)
		) {
			// nothing to update
			return $sizeName;
		}

		$size->setQuality($quality);
		$size->setCropMode($cropped);
		$size->setTargetWidth($targetWidth);
		$size->setTargetHeight($targetHeight);

		$originalFilePath = $this->getFilesystemPath($file, true);

		// initiate resizer
		$resizer = $this->getImageResizer();

		$resizer->setSourceFile($originalFilePath)
				->setOutputQuality($quality)
				->setTargetWidth($targetWidth)
				->setTargetHeight($targetHeight)
				->setCropMode($cropped);

		$expectedSize = $resizer->getExpectedSize();
		$size->setWidth($expectedSize['width']);
		$size->setHeight($expectedSize['height']);

		$resizedFileDir = $this->getFilesystemDir($file)
				. self::RESERVED_DIR_SIZE . DIRECTORY_SEPARATOR
				. $size->getFolderName();

		if ( ! file_exists($resizedFileDir)) {
			$mkdirResult = mkdir($resizedFileDir, $this->folderAccessMode, true);
			if (empty($mkdirResult)) {
				throw new Exception\RuntimeException(
						'Could not create directory for resized image');
			}
		}

		$resizedFilePath = $resizedFileDir . DIRECTORY_SEPARATOR . $file->getRealFileName();
		$resizer->setOutputFile($resizedFilePath);
		$resizer->process();

		$entityManager = $this->getDoctrineEntityManager();

		$entityManager->persist($size);
		$entityManager->flush();

		return $sizeName;
	}
281895
public function cloneImage(SourceImage $image, $orgSource, $orgDest, $stackName, Image $imageClient, OutputInterface $output)
    {
        $output->write('Cloning image: <info>'.$image->name.'</info> (<comment>'.$image->hash.'</comment>) '.$image->size.' bytes');

        $contents = null;

        if ($output->isVerbose()) {
            $output->writeln('');
            $output->write(' - Downloading image from <comment>'.$orgSource.'</comment> ... ');
        }

        if ($stackName) {
            $imageUri = $imageClient->getSourceImageUri($image->hash, $stackName);
            $contents = file_get_contents($imageUri);
        } else {
            $contents = $imageClient->getSourceImageContents($image->hash, $orgSource);
        }

        if (!$contents) {
            throw new \Exception('Can not download image from Source Organization.');
        }
        if ($output->isVerbose()) {
            $output->writeln('<info>done</info>');
        }

        if ($output->isVerbose()) {
            $output->write(' - Uploading image to <comment>'.$orgDest.'</comment> ... ');
        }

        // Uploading image to destination
        $collection = $imageClient->uploadSourceImage($contents, $image->name, $orgDest);

        if (1 != $collection->count()) {
            throw new \Exception('Error while uploading image to destination organization');
        }

        // The original HASH could not be the same as the one we get from uploading the new image, keep the latter one.
        $currentHash = $collection->getSourceImages()[0]->hash;

        if ($output->isVerbose() || $output->isVeryVerbose()) {
            if ($output->isVeryVerbose()) {
                $output->write(' (hash:'.$currentHash.') ');
            }
            $output->writeln('<info>done</info>');
        }

        // Setting Dynamic Metadata
        foreach ($image->dynamicMetadata as $name => $metadata) {
            if ($output->isVerbose()) {
                $output->write(' - Setting Dynamic Metadata <info>'.$name.'</info> to image  ... ');
            }

            $ret = $imageClient->setDynamicMetadata($metadata, $currentHash, $orgDest);
            if (!$ret) {
                throw new \Exception('Error setting DynamicMetadata for image.');
            }

            // Keep applying the metadata to the latest generated hash?
            $currentHash = $ret;

            if ($output->isVerbose() || $output->isVeryVerbose()) {
                if ($output->isVeryVerbose()) {
                    $output->write('(new-hash:'.$currentHash.') ');
                }
                $output->writeln('<info>done</info>');
            }
        }

        if (!$output->isVerbose()) {
            $output->write(' ... ');
            $output->writeln('<info>done</info>');
        }

        return true;
    }
112717
public function create()
	{
		// Set some options
		switch ($this->source)
		{
			case 'image':
				$extensions = \Config::get('validImageTypes');
				$orderField = $this->virtualFieldName('orderSRC');
				$isGallery = true;
				$isDownloads = false;
				break;
				
			case 'video':
				$extensions = \Config::get('validVideoTypes');
				$orderField = false;
				$isGallery = false;
				$isDownloads = true;
				break;
				
			case 'audio':
				$extensions = \Config::get('validAudioTypes');
				$orderField = false;
				$isGallery = false;
				$isDownloads = true;
				break;
				
			case 'custom':
				$extensions = $this->customExtension;
				$orderField = $this->virtualFieldName('orderSRC');
				$isGallery = false;
				$isDownloads = ($this->canSelectFolder) ? true : false;
				break;
				
			default:
				$extensions = \Config::get('allowedDownload');
				$orderField = $this->virtualFieldName('orderSRC');
				$isGallery = false;
				$isDownloads = true;
				break;				
		}

		if ($this->multiSource)
		{

			// The multiSRC field
			$this->generateDCA('multiSRC', array
			(
				'inputType' =>	'fileTree',
				'label'		=>	array($this->label, $this->description),
				'eval'     	=> 	array
				(
					'multiple'		=>	true,				
					'fieldType'		=>	'checkbox', 
					'orderField'	=>	$orderField,
					'files'			=>	true,
					'filesOnly'		=>	!$this->canSelectFolder,
					'extensions' 	=>	$extensions,
					'isGallery'		=>	$isGallery,
					'isDownloads'	=>	$isDownloads,
					'mandatory'		=>	($this->mandatory) ? true : false, 
					'tl_class'		=>	'clr',
				),
				'load_callback'		=> (!$orderField) ?: array
				(
					array('tl_content_elements', 'prepareOrderValue'),
				),
				'save_callback'		=> (!$orderField) ?: array
				(
					array('tl_content_elements', 'saveOrderValue'),
				),
			));

			// The orderSRC field
			if ($orderField)
			{
				$this->generateDCA('orderSRC', array(), false, false);
			}
		}
		else
		{
			// the singleSRC field
			$this->generateDCA('singleSRC', array
			(
				'inputType' =>	'fileTree',
				'label'		=>	array($this->label, $this->description),
				'eval'     	=> 	array
				(
					'fieldType'		=>	'radio', 
					'files'			=>	true, 
					'extensions' 	=>	$extensions,
					'mandatory'		=>	($this->mandatory) ? true : false, 
					'tl_class'		=>	'clr',
				),
			));
			
		}
		
		// The size field
		if ($this->source == 'image' && $this->canChangeSize)
		{
			$this->generateDCA('size', array
			(
				'inputType'			=> 'imageSize',
				'label'				=> &$GLOBALS['TL_LANG']['tl_content']['size'],
				'options'			=> $this->getImageSizeList(),
				'default'			=> $this->size,
				'reference'			=> &$GLOBALS['TL_LANG']['MSC'],
				'eval' =>	array
				(
					'rgxp' =>' natural', 
					'includeBlankOption' => false, 
					'nospace' => true, 
					'tl_class' => 'w50',
				),
				'load_callback'	=>	array
				(
					array('tl_content_elements','defaultValue')
				),
			));	
		}

		// The sortBy field
		if ($this->multiSource && $this->canChangeSortBy)
		{
			$this->generateDCA('sortBy', array
			(
				'inputType'               => 'select',
				'label'                   => &$GLOBALS['TL_LANG']['tl_content']['sortBy'],
				'options'                 => array('custom', 'name_asc', 'name_desc', 'date_asc', 'date_desc', 'random'),
				'reference'               => &$GLOBALS['TL_LANG']['tl_content'],
				'eval'                    => array
				(
					'tl_class'=>'w50'
				),
			));		
		}
	}
1139900
public function onCreate(CreateResourceEvent $event)
    {
        $request = $this->container->get('request');
        $form = $this->container->get('form.factory')->create(new FileType(true), new File());
        $form->handleRequest($request);

        if ($form->isValid()) {
            $this->handleFileCreation($form, $event);
        }

        $content = $this->container->get('templating')->render(
            'ClarolineCoreBundle:Resource:createForm.html.twig',
            array(
                'form' => $form->createView(),
                'resourceType' => $event->getResourceType()
            )
        );
        $event->setErrorFormContent($content);
        $event->stopPropagation();
    }
1197782
public function create()
    {
        /**
         * @var ImageInterface $image
         */
        $classNamespace = $this->getEntityNamespace();
        $image = new $classNamespace();
        $image
            ->setEnabled(true)
            ->setCreatedAt($this->now());

        return $image;
    }
659004
protected function sourceProperties()
    {
        $properties = Helper::imageProperties($this->source['file'], $this->source['path']);

        if ($properties['width'] !== null) {
            $this->source['width'] = $properties['width'];
            $this->source['height'] = $properties['height'];
            $this->source['aspect_ratio'] = $properties['aspect_ratio'];
        } else {
            throw new \Exception(Helper::ERROR_CALL_GETIMAGESIZE);
        }

        if ($this->canvas['width'] > $this->source['width'] || $this->canvas['height'] > $this->source['height']) {
            throw new \Exception(Helper::ERROR_UPSCALE);
        }
    }
906165
protected function initialize()
    {
        $info         = getimagesize($this->path);
        $this->width  = $info[0];
        $this->height = $info[1];
        $this->pixels = $this->width * $this->height;
        $type         = $info[2];

        switch ($type) {
            case IMAGETYPE_JPEG:
                $this->image = imagecreatefromjpeg($this->path);
                break;
            case IMAGETYPE_GIF;
                $this->image = imagecreatefromgif($this->path);
                break;
            case IMAGETYPE_PNG;
                $this->image = imagecreatefrompng($this->path);
                break;
            default:
                throw new \RuntimeException('Unsupport image type ' . $type);
        }

        imagealphablending($this->image, false);
    }
224587
function imageObject( $createMissing = true )
    {
        if ( $this->ImageObject === null or
             $this->ImageObjectRef === null )
        {
            if ( $createMissing )
            {
                if ( $this->StoredFile != '' )
                {
                    $this->process();
                }
            }
        }
        return $this->ImageObject;
    }
856248
function createGLResources(gl, glConfig) {
  const resources = {
    gl,
    buffers: {},
    textures: {},
    framebuffers: {},
    programs: {},
  };
  const buffers = glConfig.resources.buffers || [];
  const textures = glConfig.resources.textures || [];
  const framebuffers = glConfig.resources.framebuffers || [];

  // Create Buffer
  buffers.forEach((buffer) => {
    const glBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, buffer.data, gl.STATIC_DRAW);
    resources.buffers[buffer.id] = glBuffer;
  });

  // Create Texture
  textures.forEach((texture) => {
    const glTexture = gl.createTexture();
    const pixelStore = texture.pixelStore || [];
    const texParameter = texture.texParameter || [];

    gl.bindTexture(gl.TEXTURE_2D, glTexture);

    pixelStore.forEach((option) => {
      gl.pixelStorei(gl[option[0]], option[1]);
    });

    texParameter.forEach((option) => {
      gl.texParameteri(gl.TEXTURE_2D, gl[option[0]], gl[option[1]]);
    });

    resources.textures[texture.id] = glTexture;
  });

  // Create Framebuffer
  framebuffers.forEach((framebuffer) => {
    const glFramebuffer = gl.createFramebuffer();
    glFramebuffer.width = framebuffer.width;
    glFramebuffer.height = framebuffer.height;

    resources.framebuffers[framebuffer.id] = glFramebuffer;
  });

  // Create programs
  Object.keys(glConfig.programs).forEach((programName) => {
    buildShaderProgram(gl, programName, glConfig, resources);
  });

  // Add destroy function
  resources.destroy = () => {
    freeGLResources(resources);
  };

  return resources;
}
1276601
protected function createImageObject()
    {

        // Check if the file is a valid file
        if ( ! is_file( $this->originalImagePath ) ) {
            throw new Exception( sprintf( '%s: No image found.', $this->originalImagePath ) );
        }

        // Get the mimetype
        $this->imageType = exif_imagetype( $this->originalImagePath );

        // Get the width and height of image
        list($this->width, $this->height) = getimagesize($this->originalImagePath);


        // Create GD object based on the mime type
        switch ( $this->imageType ) {
            case IMAGETYPE_GIF:
                $this->image = imagecreatefromgif( $this->originalImagePath );
                break;

            case IMAGETYPE_PNG:
                $this->image = @imagecreatefrompng( $this->originalImagePath );
                break;

            case IMAGETYPE_JPEG:
                $this->image = @imagecreatefromjpeg( $this->originalImagePath );
                break;

            case IMAGETYPE_BMP:
                $this->image = imagecreatefromwbmp( $this->originalImagePath );
                break;

            // If the image is not one of the previous mimetype
            // We throw an exception
            default:
                throw new Exception( sprintf( 'This MimeType is not supported: %s. Image processed: %s', image_type_to_mime_type( $this->imageType ), $this->originalImagePath ) );
                break;
        }

        // Check if the object is successfully opened
        if( ! $this->image ) {
            throw new Exception( sprintf( 'We could not open this image: %s', $this->originalImagePath ) );
        }

    }
930799
public static function convertGDRessourceToImagick($imgRessource, $png = false)
  {
    ob_start();
    if ($png) {
      imagepng($imgRessource, null, 0);
    } else {
      imagejpeg($imgRessource, null, 100);
    }
    $blob = ob_get_clean();

    $image = new \Imagick();
    $image->readImageBlob($blob);

    return $image;
  }
1116316
public function setResource($resource)
    {
        if($this->getWorker($resource) === $this->getWorker($this->resource))
        {
            $this->resource = $resource;
        }

        $this->tmpImage[] = $tmpImage = tempnam(sys_get_temp_dir(), 'picture');

        if($this->getWorker($resource) === $this::WORKER_GD)
        {
            imagepng($resource, $tmpImage, 0);
        }
        else
        {
            $resource->writeImage($tmpImage);
        }

        if($this->isGd())
        {
            $this->resource = $this->getGdResource($tmpImage);
        }
        else
        {
            $this->resource = $this->createImagick($tmpImage);
        }
    }