Create the image in the required format

@return AbstractResize
@throws \Exception Throws an exception if there was an error creating or saving the new image
355769
public function createCopy(): AbstractResize
    {
        $this->createCanvas();

        $this->intermediate['copy'] = imagecreatefrompng($this->source['path'] . $this->source['file']);
        if ($this->intermediate['copy'] === false) {
            throw new \Exception('Call to imagecreatefrompng failed');
        }

        $this->resampleCopy();

        return $this;
    }
856050
private function createImageResource()
    {
        // We are currently using vips_image_new_from_file(), but we could consider
        // calling vips_jpegload / vips_pngload instead
        $result = /** @scrutinizer ignore-call */ vips_image_new_from_file($this->source, []);
        if ($result === -1) {
            /*throw new ConversionFailedException(
                'Failed creating new vips image from file: ' . $this->source
            );*/
            $message = /** @scrutinizer ignore-call */ vips_error_buffer();
            throw new ConversionFailedException($message);
        }

        if (!is_array($result)) {
            throw new ConversionFailedException(
                'vips_image_new_from_file did not return an array, which we expected'
            );
        }

        if (count($result) != 1) {
            throw new ConversionFailedException(
                'vips_image_new_from_file did not return an array of length 1 as we expected ' .
                '- length was: ' . count($result)
            );
        }

        $im = array_shift($result);
        return $im;
    }
1173111
public static function createFromFile( $imageFile ){
        $imageFile = realpath( $imageFile );

        if ( ! file_exists( $imageFile ) ) {
            throw new \Exception( sprintf('Could not open image file "%s"', $imageFile) );
        }

        $imagick = new \Imagick( realpath($imageFile) );
        $animated = false;
        if ($imagick->getImageIterations() > 0) {
            $animated = true;
        }

        return new self(
            $imagick,
            $imageFile,
            $imagick->getImageWidth(),
            $imagick->getImageHeight(),
            $imagick->getImageFormat(),
            $animated
        );
    }
1259853
private function createImagineInstance()
    {
        try {
            if (ImagerService::$imageDriver === 'gd') {
                return new \Imagine\Gd\Imagine();
            }

            if (ImagerService::$imageDriver === 'imagick') {
                return new \Imagine\Imagick\Imagine();
            }
        } catch (RuntimeException $e) {
            // just ignore for now
        }

        return null;
    }
831860
public function generate() {
		$tmp_pdf_path = create_tmp_file();
		$success = $this->generateWithPrince( null, null, $this->generateHtml(), $tmp_pdf_path );
		if ( true !== $success ) {
			throw new \Exception( 'Failed to create PDF file' );
		}
		$output_path = $this->timestampedFileName( 'jpg' );
		$this->convert( $tmp_pdf_path, $output_path );
		delete_transient( 'dirsize_cache' ); /** @see get_dirsize() */
		return $output_path;
	}
1321849
protected function buildImageResize() {
    $image = Image::make($this->upload_path . $this->file_name)->orientate();

    $image->resize($this->preset->width, $this->preset->height , function ($constraint) {
      $constraint->aspectRatio();
      $constraint->upsize();
    });

    //if background_color is not set, do not resizeCanvas with black color, to avoid black zones in images. 
    if(isset($this->preset->background_color))
    {
      $image->resizeCanvas($this->preset->width, $this->preset->height, 'center', FALSE, $this->preset->background_color);
    }
    
    return $image;
  }
1354764
private function createImage() {
		if ( $this->_image != NULL ) imagedestroy( $this->_image );
		$this->_image = imagecreatetruecolor($this->_config['w'], $this->_config['h']);
		switch ( mt_rand() % 4 ) {
		case 0: $_bg = imagecolorallocate($this->_image, 250, 250, 250); break;
		case 1: $_bg = imagecolorallocate($this->_image, 255, 252, 232); break;
		case 2: $_bg = imagecolorallocate($this->_image, 254, 245, 243); break;
		case 3: $_bg = imagecolorallocate($this->_image, 233, 255, 242); break;
		}
		imagefilledrectangle($this->_image, 0, 0, $this->_config['w'], $this->_config['h'], $_bg);
		//imagefilter($this->_image, IMG_FILTER_EMBOSS);
		
		switch ( mt_rand() % 5 ) {
            case 0:	$_color = imagecolorallocate($this->_image, 128, 128, 128);	break;	//gray
            case 1:	$_color = imagecolorallocate($this->_image, 16, 9, 140);	break;	//blue
            case 2: $_color = imagecolorallocate($this->_image, 65, 125, 0);	break;	//green
            case 3: $_color = imagecolorallocate($this->_image, 255, 75, 45);	break;	//read
            case 4: $_color = imagecolorallocate($this->_image, 238, 175, 7);	break;	//orange
		}
		//$_color = imagecolorallocate($this->_image, 238, 175, 7);
		$_font = __DIR__ . '/fonts/ariblk.ttf';
		//$_angle = (mt_rand() & 0x01) == 0 ? mt_rand() % 30 : - mt_rand() % 30;
		
		//draw the code chars
		$_size = count($this->_codes);
		$_xstep = ($this->_config['w'] - 2 * $this->_config['x']) / $_size;
		$_ret = 0;
		for ( $i = 0; $i < $_size; $i++ ) {
			$_ret = mt_rand();
			imagettftext($this->_image, $this->_config['f'],
					($_ret & 0x01) == 0 ? $_ret % 30 : - ($_ret % 30),
						$this->_config['x'] + $i * $_xstep, $this->_config['y'],
							$_color, $_font, $this->_codes[$i]);
		}
	}
906876
final public function resizeImage($width = null, $height = null)
	{
		if (is_int($width) and is_int($height)) {
			$new_image = imagecreatetruecolor($width, $height);
			imagecopyresampled(
				$new_image,
				$this->_image_handle,
				0,
				0,
				0,
				0,
				$width,
				$height,
				$this->imageWidth(),
				$this->imageHeight()
			);
			if (is_resource($new_image)) {
				$this->_image_handle = $new_image;
			}
		}
		return $this;
	}
826315
private function createImagineInstance()
    {
        $extension = mb_strtolower(\Craft::$app->getConfig()->getGeneral()->imageDriver);
        
        try {
            if ($extension === 'gd') {
                return new \Imagine\Gd\Imagine();
            }

            if ($extension === 'imagick') {
                return new \Imagine\Imagick\Imagine();
            }
        } catch (RuntimeException $e) {
            // just ignore for now
        }

        return null;
    }
1239009
public function create()
    {
        $File = new File($this->path());

        if (!$File->readable()) {
            $minifier = $this->type === 'css' ? new Minify\CSS() : new Minify\JS();
            array_map([$minifier, 'add'], $this->paths);

            //Writes the file
            $success = $File->write($minifier->minify());
            is_true_or_fail($success, __d('assets', 'Failed to create file {0}', rtr($this->path())));
        }

        return $this->filename();
    }
279802
public function save() : AbstractResize
    {
        if ($this->file === null) {
            $this->file = str_replace($this->extension, '-copy' . $this->extension, $this->source['file']);
        }
        if ($this->path === null) {
            $this->path = $this->source['path'];
        }

        $this->saveFile();

        return $this;
    }
579377
public function create()
    {
        //queries to run
        $queries = [];

        //translate model data to sql data
        if (is_null($this->schema)) {
            throw Exception::forNoSchema();
        }

        $data = $this->schema->toSql();

        //determine the create schema
        $query = $this
            ->resource
            ->getCreateQuery($data['name'])
            ->addPrimaryKey($data['primary'])
            ->addField($data['primary'], [
                'type' => 'int(10)',
                'null' => false,
                'attribute' => 'UNSIGNED',
                'auto_increment' => true,
            ]);

        foreach ($data['columns'] as $name => $column) {
            $attributes = ['type' => $column['type']];

            if (isset($column['length'])) {
                $attributes['type'] .= '(' . $column['length'] . ')';
            }

            if (isset($column['default']) && strlen($column['default'])) {
                $attributes['default'] = $column['default'];
            } else if (!isset($column['required']) || !$column['required']) {
                $attributes['null'] = true;
            }

            if (isset($column['required']) && $column['required']) {
                $attributes['null'] = false;
            }

            if (isset($column['attribute']) && $column['attribute']) {
                $attributes['attribute'] = $column['attribute'];
            }

            $query->addField($name, $attributes);

            if (isset($column['index']) && $column['index']) {
                $query->addKey($name, [$name]);
            }

            if (isset($column['unique']) && $column['unique']) {
                $query->addUniqueKey($name, [$name]);
            }

            if (isset($column['primary']) && $column['primary']) {
                $query->addPrimaryKey($name);
            }
        }

        $queries[] = 'DROP TABLE IF EXISTS `' . $data['name'] . '`;';
        $queries[] = (string) $query;

        //determine the relation schema
        foreach ($data['relations'] as $table => $relation) {
            $query = $this->resource->getCreateQuery($table);

            $query->addPrimaryKey($relation['primary1']);
            $query->addField($relation['primary1'], [
                'type' => 'int(10)',
                'null' => false,
                'attribute' => 'UNSIGNED'
            ]);

            $query->addPrimaryKey($relation['primary2']);
            $query->addField($relation['primary2'], [
                'type' => 'int(10)',
                'null' => false,
                'attribute' => 'UNSIGNED'
            ]);

            $queries[] = 'DROP TABLE IF EXISTS `'. $table . '`;';
            $queries[] = (string) $query;
        }

        //execute queries
        $results = [];
        foreach ($queries as $query) {
            $results[] = [
                'query' => $query,
                'results' => $this->resource->query($query)
            ];
        }

        return $results;
    }
289593
private function upload_image()
    {

        /* validate the image */
        $validation    = Validator::make($this->image, array($this->input => $this->rules));
        $errors        = array();
        $original_name = $this->image[$this->input]->getClientOriginalName();
        $path          = '';
        $filename      = '';
        $resizes       = '';

        if ($validation->fails()) {
            /* use the messages object for the erros */
            $errors = implode('. ', $validation->messages()->all());
        } else {
            if ($this->random) {
                if (is_callable($this->random_cb)) {
                    $filename = call_user_func($this->random_cb, $original_name);
                } else {
                    $ext      = File::extension($original_name);
                    $filename = $this->generate_random_filename().'.'.$ext;
                }
            } else {
                $filename = $original_name;
            }

            /* upload the file */
            $save = $this->image[$this->input]->move($this->path, $filename);
            //$save = Input::upload($this->input, $this->path, $filename);

            if ($save) {
                $path = $this->path.$filename;

                if (is_array($this->image_sizes)) {
                    $resizer = new Resize();
                    $resizes = $resizer->create($save, $this->path, $filename, $this->image_sizes);
                }
            } else {
                $errors = 'Could not save image';
            }
        }

        return compact('errors', 'path', 'filename', 'original_name', 'resizes');
    }
241541
public function make()
    {
        $this->image->encode($this->format, $this->quality);
        $data = $this->image->getEncoded();
        $mime = finfo_buffer(finfo_open(FILEINFO_MIME_TYPE), $data);
        $length = strlen($data);

        if (function_exists('app') && is_a($app = app(), 'Illuminate\Foundation\Application')) {

            $response = \Illuminate\Support\Facades\Response::make($data);
            $response->header('Content-Type', $mime);
            $response->header('Content-Length', $length);

        } else {

            header('Content-Type: ' . $mime);
            header('Content-Length: ' . $length);
            $response = $data;
        }

        return $response;
    }
823518
private function createImageResource()
    {
        // In case of failure, image will be false

        $mimeType = $this->getMimeTypeOfSource();

        if ($mimeType == 'image/png') {
            $image = imagecreatefrompng($this->source);
            if ($image === false) {
                throw new ConversionFailedException(
                    'Gd failed when trying to load/create image (imagecreatefrompng() failed)'
                );
            }
            return $image;
        }

        if ($mimeType == 'image/jpeg') {
            $image = imagecreatefromjpeg($this->source);
            if ($image === false) {
                throw new ConversionFailedException(
                    'Gd failed when trying to load/create image (imagecreatefromjpeg() failed)'
                );
            }
            return $image;
        }

        /*
        throw new InvalidInputException(
            'Unsupported mime type:' . $mimeType
        );*/
    }
287188
public function evaluate()
    {
        $asset = $this->getAsset();
        $preset = $this->getPreset();

        if (!$asset instanceof AssetInterface) {
            throw new \Exception('No asset given for rendering.', 1415184217);
        }
        if (!empty($preset)) {
            $thumbnailConfiguration = $this->thumbnailService->getThumbnailConfigurationForPreset($preset);
        } else {
            $thumbnailConfiguration = new ThumbnailConfiguration($this->getWidth(), $this->getMaximumWidth(), $this->getHeight(), $this->getMaximumHeight(), $this->getAllowCropping(), $this->getAllowUpScaling(), $this->getAsync(), $this->getQuality(), $this->getFormat());
        }
        $request = $this->getRuntime()->getControllerContext()->getRequest();
        $thumbnailData = $this->assetService->getThumbnailUriAndSizeForAsset($asset, $thumbnailConfiguration, $request);
        if ($thumbnailData === null) {
            return '';
        }
        return $thumbnailData['src'];
    }
125309
protected function recreateImageSizes(Image $file)
	{
		if ( ! $file instanceof Image) {
			throw new Exception\RuntimeException('Image entity expected');
		}

		$sizes = $file->getImageSizeCollection();
		if ( ! $sizes->isEmpty()) {
			foreach ($sizes as $size) {
				$sizeName = $size->getName();
				$filePath = $this->getImagePath($file, $sizeName);

				if (file_exists($filePath)) {
					
					$result = unlink($filePath);

					if ( ! $result) {
						throw new Exception\RuntimeException("Could not delete '$filePath' from file storage");
					}
				}

				$this->createResizedImage($file, $size->getTargetWidth(), $size->getTargetHeight(), $size->getCropMode(), $size->getQuality(), true);
			}
		}
	}