Пример #1
2
 public function making($dst_w, $dst_h)
 {
     $thumb_img = imagecreatetruecolor($dst_w, $dst_h);
     imagecopyresampled($thumb_img, $this->image, 0, 0, 0, 0, $dst_w, $dst_h, $this->width, $this->height);
     ob_start();
     switch ($this->_mimetype) {
         case "gd2":
             imagegd2($thumb_img, null, 100);
             break;
         case "gd":
             imagegd($thumb_img, null, 100);
             break;
         case "gif":
             imagegif($thumb_img, null, 100);
             break;
         case "jpeg":
             imagejpeg($thumb_img, null, 100);
             break;
         case "jpg":
             imagejpeg($thumb_img, null, 100);
             break;
         case "png":
             imagepng($thumb_img, null, 9);
             break;
         case "webp":
             imagewebp($thumb_img, null, 100);
             break;
         default:
             throw new \yii\base\NotSupportedException("Unsupport imageX method!");
             break;
     }
     imagedestroy($this->image);
     //destory origin
     return ob_get_clean();
     //返回二进制数据流
 }
Пример #2
1
 /**
  * {@inheritdoc}
  */
 public function generate($output, $outputPath = null)
 {
     imagewebp($output, $outputPath);
 }
Пример #3
0
<?php

$filename = './php.webp';
// Create a blank image and add some text
$im = imagecreatetruecolor(380, 60);
$text_color = imagecolorallocate($im, 233, 66, 91);
imagestring($im, 2, 9, 9, 'I\'ve got 99 problems but WebP ain\'t one.', $text_color);
// Save the image
imagewebp($im, $filename, 99);
imagedestroy($im);
// We could check the MD5-hash here but maybe libvpx will get some
// improvements in the future that would change the output file.
// We just check if the file is a valid WebP-File and has
// approximately the right size.
echo floor(filesize($filename) / 100) * 100, "\n";
$fp = fopen($filename, 'r');
// read 14 Bytes from the WebP-File, that contains the header
$data = fread($fp, 14);
// remove non-ASCII chars
echo preg_replace('/[[:^print:]]/', '?', $data);
fclose($fp);
unlink($filename);
Пример #4
0
for ($i = 0; $i < $loop_count; $i++) {
    ImageString($image, $_font, align($exploded_string[$i], $_align), $i * imagefontheight($_font), $exploded_string[$i], $_color);
}
if ($_str_has_auth) {
    ImageString($image, $_font, align("-- " . $exploded_string[$loop_count], opp_align($_align)), $loop_count * imagefontheight($_font), "-- " . $exploded_string[$loop_count], $_color);
}
//Tell the browser what kind of file is come in
header("Content-Type: image/" . $_type);
//$_type_s = array("jpeg", "gif", "png", "webp");
switch ($_type) {
    case "gif":
        imagegif($image);
        break;
    case "png":
        imagepng($image);
        break;
    case "webp":
        $img_create_ret = imagewebp($image);
        if ($img_create_ret == false) {
            //fallback?
            imagepng($image);
        }
        break;
    default:
        //jpeg as default
        imagejpeg($image);
        break;
}
//Free up resources
ImageDestroy($image);
exit;
Пример #5
0
 /**
  * Saves image as webp
  *
  * @param $imageInstance
  * @param $path
  * @param $sourceExtension
  * @param $saveOptions
  * @throws Exception
  */
 private function _saveAsWebp($imageInstance, $path, $sourceExtension, $saveOptions)
 {
     if ($this->getSetting('useCwebp')) {
         // save temp file
         $tempFile = $this->_saveTemporaryFile($imageInstance, $sourceExtension);
         // convert to webp with cwebp
         $command = escapeshellcmd($this->getSetting('cwebpPath') . ' ' . $this->getSetting('cwebpOptions') . ' -q ' . $saveOptions['webp_quality'] . ' ' . $tempFile . ' -o ' . $path);
         $r = shell_exec($command);
         if (!IOHelper::fileExists($path)) {
             throw new Exception(Craft::t('Save operation failed'));
         }
         // delete temp file
         IOHelper::deleteFile($tempFile);
     } else {
         if ($this->imageDriver === 'gd') {
             $instance = $imageInstance->getGdResource();
             if (false === \imagewebp($instance, $path, $saveOptions['webp_quality'])) {
                 throw new Exception(Craft::t('Save operation failed'));
             }
             // Fix for corrupt file bug (http://stackoverflow.com/questions/30078090/imagewebp-php-creates-corrupted-webp-files)
             if (filesize($path) % 2 == 1) {
                 file_put_contents($path, "", FILE_APPEND);
             }
         }
         if ($this->imageDriver === 'imagick') {
             $instance = $imageInstance->getImagick();
             $instance->setImageFormat('webp');
             $instance->setImageAlphaChannel(\Imagick::ALPHACHANNEL_ACTIVATE);
             $instance->setBackgroundColor(new \ImagickPixel('transparent'));
             $instance->setImageCompressionQuality($saveOptions['webp_quality']);
             $imagickOptions = $saveOptions['webp_imagick_options'];
             if ($imagickOptions && count($imagickOptions) > 0) {
                 foreach ($imagickOptions as $key => $val) {
                     $instance->setOption('webp:' . $key, $val);
                 }
             }
             $instance->writeImage($path);
         }
     }
 }
Пример #6
0
 public function generateFilePreview($file_id)
 {
     debug("generating preview");
     $file_id = intval($file_id);
     $file_info = $this->getFileInfoById($file_id);
     if ($file_info == null) {
         debug("cannot generate preview, file_id not found");
         return false;
     }
     //direct path
     $realpath = realpath(self::getFilesFolderName() . "/" . $file_info->fullpath);
     debug("realpath: " . $realpath);
     $info = pathinfo($realpath);
     //to extract extension
     $previewWidth = self::$PREVIEW_IMAGE_SIZE;
     $ext = strtolower($info['extension']);
     $img = null;
     switch ($ext) {
         case 'jpeg':
         case 'jpg':
             $img = imagecreatefromjpeg($realpath);
             break;
         case 'png':
             $img = imagecreatefrompng($realpath);
             break;
         case 'webp':
             $img = imagecreatefromwebp($realpath);
             break;
         default:
             debug("cannot preview, unknown extension: " . $ext);
             return false;
     }
     if (!$img) {
         debug("Image couldnt be loaded: " . $realpath);
         return false;
     }
     $width = imagesx($img);
     $height = imagesy($img);
     // calculate preview size
     $new_width = $previewWidth;
     $new_height = floor($height * ($previewWidth / $width));
     // create a new temporary image
     $tmp_img = imagecreatetruecolor($new_width, $new_height);
     // copy and resize old image into new image
     imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
     $picpath = $file_info->unit_name . "/" . $file_info->folder;
     $tn_filename = PREVIEW_PREFIX . $file_info->filename . PREVIEW_SUFIX;
     $tn_path = $this->getFilesFolderName() . "/" . $picpath . "/" . $tn_filename;
     // save preview into a file
     $result = null;
     if (PREVIEW_SUFIX == ".png") {
         $result = imagepng($tmp_img, $tn_path);
     } else {
         if (PREVIEW_SUFIX == ".jpg") {
             $result = imagejpeg($tmp_img, $tn_path);
         } else {
             if (PREVIEW_SUFIX == ".webp") {
                 $result = imagewebp($tmp_img, $tn_path);
             } else {
                 debug("unsupported preview extension");
                 return false;
             }
         }
     }
     if (!$result) {
         debug("Error saving generated preview: " . $tn_path);
         return false;
     }
     debug("preview generated: " . $tn_path);
     return true;
 }
Пример #7
0
 /**
  * Resizes an image file
  * 
  * @param string $sourceFilename The image file to resize
  * @param string $destinationFilename The filename where the result image will be saved
  * @param array $options Resize options. You can resize the file by providing "width", "height" or both.
  * @throws \InvalidArgumentException
  * @throws \Exception
  * @return void No value is returned
  */
 public function resize($sourceFilename, $destinationFilename, $options = [])
 {
     if (!is_string($sourceFilename)) {
         throw new \InvalidArgumentException('The sourceFilename argument must be of type string');
     }
     $sourceFilename = realpath($sourceFilename);
     if ($sourceFilename === false) {
         throw new \InvalidArgumentException('The sourceFilename specified does not exist');
     }
     if (!is_string($destinationFilename)) {
         throw new \InvalidArgumentException('The destinationFilename argument must be of type string');
     }
     if (!is_array($options)) {
         throw new \InvalidArgumentException('The options argument must be of type array');
     }
     if (isset($options['width']) && (!is_int($options['width']) || $options['width'] < 1 || $options['width'] > 100000)) {
         throw new \InvalidArgumentException('The width value must be higher than 0 and lower than 100001');
     }
     if (isset($options['height']) && (!is_int($options['height']) || $options['height'] < 1 || $options['height'] > 100000)) {
         throw new \InvalidArgumentException('The height value must be higher than 0 and lower than 100001');
     }
     $outputType = null;
     $sourcePathInfo = pathinfo($sourceFilename);
     $destinationPathInfo = pathinfo($destinationFilename);
     if (isset($destinationPathInfo['extension'])) {
         $extension = $destinationPathInfo['extension'];
         if ($extension === 'png') {
             $outputType = 'png';
         } elseif ($extension === 'gif') {
             $outputType = 'gif';
         } elseif ($extension === 'jpg' || $extension === 'jpeg') {
             $outputType = 'jpg';
         } elseif ($extension === 'webp') {
             $outputType = 'webp';
         }
     }
     if ($outputType !== 'png' && $outputType !== 'gif' && $outputType !== 'jpg' && $outputType !== 'webp') {
         throw new \InvalidArgumentException('The output format is not valid');
     }
     try {
         if (isset($sourcePathInfo['extension']) && $sourcePathInfo['extension'] === 'webp') {
             $sourceImageSize = $this->getSize($sourceFilename);
             $sourceImageWidth = $sourceImageSize[0];
             $sourceImageHeight = $sourceImageSize[1];
             $sourceImageMimeType = 'image/webp';
         } else {
             $sourceImageInfo = getimagesize($sourceFilename);
             if (!is_array($sourceImageInfo)) {
                 throw new \InvalidArgumentException('Cannot get source image size');
             }
             $sourceImageWidth = $sourceImageInfo[0];
             $sourceImageHeight = $sourceImageInfo[1];
             $sourceImageMimeType = $sourceImageInfo['mime'];
         }
     } catch (\Exception $e) {
         throw new \InvalidArgumentException('Unknown error (' . $e->getMessage() . ')');
     }
     $width = isset($options['width']) ? $options['width'] : null;
     $height = isset($options['height']) ? $options['height'] : null;
     if ($width === null && $height === null) {
         $width = $sourceImageWidth;
         $height = $sourceImageHeight;
     } elseif ($width === null && $height !== null) {
         $width = (int) floor($sourceImageWidth / $sourceImageHeight * $height);
     } elseif ($height === null && $width !== null) {
         $height = (int) floor($sourceImageHeight / $sourceImageWidth * $width);
     }
     if ($sourceImageWidth === $width && $sourceImageHeight === $height) {
         copy($sourceFilename, $destinationFilename);
     } else {
         $sourceImage = null;
         if ($sourceImageMimeType === 'image/jpeg' && function_exists('imagecreatefromjpeg')) {
             $sourceImage = imagecreatefromjpeg($sourceFilename);
         } elseif ($sourceImageMimeType === 'image/png' && function_exists('imagecreatefrompng')) {
             $sourceImage = imagecreatefrompng($sourceFilename);
         } elseif ($sourceImageMimeType === 'image/gif' && function_exists('imagecreatefromgif')) {
             $sourceImage = imagecreatefromgif($sourceFilename);
         } elseif ($sourceImageMimeType === 'image/webp' && function_exists('imagecreatefromwebp')) {
             $sourceImage = imagecreatefromwebp($sourceFilename);
         }
         if (!$sourceImage) {
             throw new \InvalidArgumentException('Cannot read the source image');
         }
         $result = false;
         try {
             $resultImage = imagecreatetruecolor($width, $height);
             imagealphablending($resultImage, false);
             imagesavealpha($resultImage, true);
             imagefill($resultImage, 0, 0, imagecolorallocatealpha($resultImage, 0, 0, 0, 127));
             $widthRatio = $sourceImageWidth / $width;
             $heightRatio = $sourceImageHeight / $height;
             $resizedImageHeight = $height;
             $resizedImageWidth = $width;
             if ($widthRatio > $heightRatio) {
                 $resizedImageWidth = ceil($sourceImageWidth / $heightRatio);
             } else {
                 $resizedImageHeight = ceil($sourceImageHeight / $widthRatio);
             }
             $destinationX = -($resizedImageWidth - $width) / 2;
             $destinationY = -($resizedImageHeight - $height) / 2;
             if (imagecopyresampled($resultImage, $sourceImage, floor($destinationX), floor($destinationY), 0, 0, $resizedImageWidth, $resizedImageHeight, $sourceImageWidth, $sourceImageHeight)) {
                 if ($outputType == 'jpg') {
                     $result = imagejpeg($resultImage, $destinationFilename, 100);
                 } elseif ($outputType == 'png') {
                     $result = imagepng($resultImage, $destinationFilename, 9);
                 } elseif ($outputType == 'gif') {
                     $result = imagegif($resultImage, $destinationFilename);
                 } elseif ($outputType == 'webp') {
                     $result = imagewebp($resultImage, $destinationFilename);
                 }
             }
             imagedestroy($resultImage);
         } catch (\Exception $e) {
         }
         imagedestroy($sourceImage);
         if (!$result) {
             throw new \Exception('');
         }
     }
 }
Пример #8
0
 /**
  * 
  * @param type $bytes
  * @param type $mimeType
  * @param type $comPrefixo
  * @return string
  */
 private static function getImagemBase64ComPrefixo($bytes, $mimeType, $comPrefixo = false, $tipo = 'image/webp')
 {
     // converte a imagem
     if ($mimeType !== 'image/webp') {
         $data = imagecreatefromstring($bytes);
         ob_start();
         if (function_exists('imagewebp') && $tipo === 'image/webp') {
             imagewebp($data);
         } elseif (function_exists('imagegif') && $tipo === 'image/gif') {
             imagegif($data);
         } elseif (function_exists('imagepng') && $tipo === 'image/png') {
             // sem compressão
             imagepng($data, null, 0);
         } else {
             $tipo = 'image/jpeg';
             // melhor qualidade
             imagejpeg($data, null, 100);
         }
         $bytes = ob_get_contents();
         ob_end_clean();
     }
     $arquivo = base64_encode($bytes);
     if ($comPrefixo) {
         $retorno = 'data:' . $tipo . ';base64,' . $arquivo;
     } else {
         $retorno = $arquivo;
     }
     return $retorno;
 }
Пример #9
0
 protected function _types()
 {
     $type = strtolower($this->type);
     if (!empty($this->save)) {
         $save = suffix($this->save, '.' . $type);
         $this->result['path'] = $save;
     } else {
         $save = NULL;
     }
     if ($type === 'jpeg') {
         if ($this->quality === 0) {
             $this->quality = 80;
         }
         imagejpeg($this->canvas, $save, $this->quality);
     } elseif ($type === 'png') {
         if ($this->quality === 0) {
             $this->quality = 8;
         }
         imagepng($this->canvas, $save, $this->quality);
     } elseif ($type === 'gif') {
         imagegif($this->canvas, $save);
     } elseif ($type === 'gd') {
         imagegd($this->canvas, $save);
     } elseif ($type === 'gd2') {
         imagegd2($this->canvas, $save, $this->quality);
     } elseif ($type === 'wbmp') {
         imagewbmp($this->canvas, $save, $this->quality);
     } elseif ($type === 'xbm') {
         imagexbm($this->canvas, $save, $this->quality);
     } elseif ($type === 'xpm') {
         imagexpm($this->canvas, $save, $this->quality);
     } elseif ($type === 'webp') {
         imagewebp($this->canvas, $save, $this->quality);
     }
     return $this;
 }
Пример #10
0
 /**
  * Transform an image into another image according to params.
  *
  * @internal The args are currently already checked in the controller.
  *
  * @param array $args List of arguments for the transformation.
  * @return string|null The filepath to the temp image if success.
  */
 public function transform(array $args = array())
 {
     if (empty($args)) {
         return;
     }
     $this->_args = $args;
     $args =& $this->_args;
     if (!$this->checkMediaType($args['source']['mime_type']) || !$this->checkMediaType($args['format']['feature'])) {
         return;
     }
     $sourceGD = $this->_loadImageResource($args['source']['filepath']);
     if (empty($sourceGD)) {
         return;
     }
     // Get width and height if missing.
     if (empty($args['source']['width']) || empty($args['source']['height'])) {
         $args['source']['width'] = imagesx($sourceGD);
         $args['source']['height'] = imagesy($sourceGD);
     }
     $extraction = $this->_prepareExtraction();
     if (!$extraction) {
         imagedestroy($sourceGD);
         return;
     }
     list($sourceX, $sourceY, $sourceWidth, $sourceHeight, $destinationWidth, $destinationHeight) = $extraction;
     $destinationGD = imagecreatetruecolor($destinationWidth, $destinationHeight);
     // The background is normally useless, but it's costless.
     $black = imagecolorallocate($destinationGD, 0, 0, 0);
     imagefill($destinationGD, 0, 0, $black);
     $result = imagecopyresampled($destinationGD, $sourceGD, 0, 0, $sourceX, $sourceY, $destinationWidth, $destinationHeight, $sourceWidth, $sourceHeight);
     if ($result === false) {
         imagedestroy($sourceGD);
         imagedestroy($destinationGD);
         return;
     }
     // Rotation.
     switch ($args['rotation']['feature']) {
         case 'noRotation':
             break;
         case 'rotationBy90s':
             switch ($args['rotation']['degrees']) {
                 case 90:
                 case 270:
                     $i = $destinationWidth;
                     $destinationWidth = $destinationHeight;
                     $destinationHeight = $i;
                     // GD uses anticlockwise rotation.
                     $degrees = $args['rotation']['degrees'] == 90 ? 270 : 90;
                     // Continues below.
                 // Continues below.
                 case 180:
                     $degrees = isset($degrees) ? $degrees : 180;
                     // imagerotate() returns a resource, not a boolean.
                     $destinationGDrotated = imagerotate($destinationGD, $degrees, 0);
                     imagedestroy($destinationGD);
                     if ($destinationGDrotated === false) {
                         imagedestroy($sourceGD);
                         return;
                     }
                     $destinationGD =& $destinationGDrotated;
                     break;
             }
             break;
         case 'rotationArbitrary':
             // Currently not managed.
         // Currently not managed.
         default:
             imagedestroy($sourceGD);
             imagedestroy($destinationGD);
             return;
     }
     // Quality.
     switch ($args['quality']['feature']) {
         case 'default':
             break;
         case 'color':
             // No change, because only one image is managed.
             break;
         case 'gray':
             $result = imagefilter($destinationGD, IMG_FILTER_GRAYSCALE);
             if ($result === false) {
                 imagedestroy($sourceGD);
                 imagedestroy($destinationGD);
                 return;
             }
             break;
         case 'bitonal':
             $result = imagefilter($destinationGD, IMG_FILTER_GRAYSCALE);
             $result = imagefilter($destinationGD, IMG_FILTER_CONTRAST, -65535);
             if ($result === false) {
                 imagedestroy($sourceGD);
                 imagedestroy($destinationGD);
                 return;
             }
             break;
         default:
             imagedestroy($sourceGD);
             imagedestroy($destinationGD);
             return;
     }
     // Save resulted resource into the specified format.
     // TODO Use a true name to allow cache, or is it managed somewhere else?
     $destination = tempnam(sys_get_temp_dir(), 'uv_');
     switch ($args['format']['feature']) {
         case 'image/jpeg':
             $result = imagejpeg($destinationGD, $destination);
             break;
         case 'image/png':
             $result = imagepng($destinationGD, $destination);
             break;
         case 'image/gif':
             $result = imagegif($destinationGD, $destination);
             break;
         case 'image/webp':
             $result = imagewebp($destinationGD, $destination);
             break;
     }
     imagedestroy($sourceGD);
     imagedestroy($destinationGD);
     return $result ? $destination : null;
 }
Пример #11
0
 /**
  * Encodes an image to the given format.
  *
  * @param resource $bitmap Image DG resource
  * @param string|null $file File to which image should be written. If null, byte code of the encoded image will be
  *  printed to the main output.
  * @param int $type Image format to encode. Value is one of global constants IMAGETYPE_*.
  * @param float $quality Save quality. 0 — small size, 1 — good quality.
  * @return bool Is the image encoded successfully
  * @throws \InvalidArgumentException Given format is not supported
  */
 protected static function saveImage($bitmap, $file, $type, $quality = 0.75)
 {
     switch ($type) {
         case IMAGETYPE_JPEG:
             return @imagejpeg($bitmap, $file, $quality * 100);
         case IMAGETYPE_BMP:
         case IMAGETYPE_WBMP:
             return @imagewbmp($bitmap, $file);
         case IMAGETYPE_PNG:
             @imagealphablending($bitmap, false);
             @imagesavealpha($bitmap, true);
             $result = @imagepng($bitmap, $file, 9);
             @imagealphablending($bitmap, true);
             return $result;
         case IMAGETYPE_GIF:
             return @imagegif($bitmap, $file);
         case IMAGETYPE_WEBP:
             if (function_exists('imagewebp')) {
                 return @imagewebp($bitmap, $file);
             }
             break;
     }
     throw new \InvalidArgumentException('Given image type `' . $type . '` is unknown.');
 }
Пример #12
0
 /**
  * This method produces the needed WebP images, upon upload and/or upon thumbnail regeneration
  *
  * @param array $params: id_image (int), id_product (int) and image_type (string)
  * @return boolean: true if all images were succesfully created, false if not.
  */
 public function hookActionWatermark($params)
 {
     $check = true;
     $image = new Image($params['id_image']);
     $image->id_product = $params['id_product'];
     $return = array();
     // loop over all image types and create the associated WebP thumbnail
     foreach (ImageType::getImagesTypes('products') as $imageType) {
         $check = true;
         $img_basename = _PS_PROD_IMG_DIR_ . $image->getExistingImgPath() . '-' . Tools::stripslashes($imageType['name']);
         $img = $this->getImageByType($img_basename . '.jpg');
         if ($img !== false) {
             if (!imagewebp($img, $img_basename . '.webp')) {
                 $this->insertLogMessage($this->name, 3, sprintf($this->l('%s could not be written to the filesystem.'), $img_basename . '.webp'));
                 $check = false;
             } else {
                 // based on an open bug, ID: 66590, https://bugs.php.net/bug.php?id=66590 we need to fix a few things regarding
                 // the filesize of the webp image. Hence this method call.
                 if (!$this->fixWebP($img_basename . '.webp')) {
                     // something went wrong and we should report such
                     $this->insertLogMessage($this->name, 3, sprintf($this->l('%s could not be written to the filesystem.'), $img_basename . '.webp'));
                     $check = false;
                 } else {
                     // we can finally report success!
                     $this->insertLogMessage($this->name, 0, sprintf($this->l('%s successfully written to the filesystem.'), $img_basename . '.webp'));
                 }
             }
             imagedestroy($img);
         } else {
             $check = false;
             $this->insertLogMessage($this->name, 2, sprintf($this->l('%s was not found on the filesystem.'), $img_basename . '.jpg'));
         }
         $return[] = $check;
     }
     return in_array(false, $return) ? false : true;
 }
Пример #13
0
<?php

$filename = './php.webp';
// Create a blank image and add some text
$im = imagecreatetruecolor(380, 60);
$text_color = imagecolorallocate($im, 233, 66, 91);
imagestring($im, 2, 9, 9, 'I\'ve got 99 problems but WebP ain\'t one.', $text_color);
// Save the image
imagewebp($im, $filename);
imagedestroy($im);
$size = filesize($filename) - 7;
//Subtract FourCC + length header
$fp = fopen($filename, 'r');
// read 14 Bytes from the WebP-File, that contains the header
$header = fread($fp, 14);
$header = unpack("A4fourcc/L1length/A4chunkheader", $header);
if ($header["fourcc"] != "RIFF") {
    echo "Invalid FourCC in created image file\n";
}
if ($header["length"] != $size) {
    echo "The length specified in the image header is different from the actual size: ({$header['length']} != {$size})\n";
}
fclose($fp);
unlink($filename);
echo "OK!\n";
Пример #14
0
 public function resizeImage(File $file, $targetWidth, $targetHeight, $allowedStep = 10, $targetFormat = 'png')
 {
     if (!in_array($targetFormat, $this->formats)) {
         $targetFormat = 'png';
     }
     $targetHeight = (int) round($targetHeight / $allowedStep) * $allowedStep;
     $targetWidth = (int) round($targetWidth / $allowedStep) * $allowedStep;
     $filename = $file->getFullPath($this->container->getParameter('uebb.hateoas.upload_dir'));
     try {
         list($sourceWidth, $sourceHeight, $type) = getimagesize($filename);
     } catch (\Exception $e) {
         throw new NotFoundHttpException('', $e);
     }
     if ($targetWidth === 0) {
         $targetWidth = $sourceWidth;
     }
     if ($targetHeight === 0) {
         $targetHeight = $sourceHeight;
     }
     $sourceRatio = $sourceWidth / $sourceHeight;
     $targetRatio = $targetWidth / $targetHeight;
     if ($sourceWidth <= $targetWidth && $sourceHeight <= $targetHeight) {
         $targetWidth = $sourceWidth;
         $targetHeight = $sourceHeight;
     } else {
         if ($targetRatio > $sourceRatio) {
             $targetWidth = (int) ($targetHeight * $sourceRatio);
         } else {
             if ($targetRatio < $sourceRatio) {
                 $targetHeight = (int) ($targetWidth / $sourceRatio);
             }
         }
     }
     $cache_filename = $file->getFullPath($this->container->getParameter('uebb.hateoas.cache_dir')) . '-' . strval($targetWidth) . 'x' . strval($targetHeight) . '.' . $targetFormat;
     if (!is_file($cache_filename)) {
         switch ($type) {
             case IMAGETYPE_GIF:
                 $sourceImage = imagecreatefromgif($filename);
                 break;
             case IMAGETYPE_JPEG:
                 $sourceImage = imagecreatefromjpeg($filename);
                 break;
             case IMAGETYPE_PNG:
                 $sourceImage = imagecreatefrompng($filename);
                 break;
             default:
                 throw new NotFoundHttpException();
                 break;
         }
         $targetImage = imagecreatetruecolor($targetWidth, $targetHeight);
         imagecopyresampled($targetImage, $sourceImage, 0, 0, 0, 0, $targetWidth, $targetHeight, $sourceWidth, $sourceHeight);
         $dir = dirname($cache_filename);
         if (!is_dir($dir)) {
             mkdir($dir, 0770, true);
         }
         switch ($targetFormat) {
             case 'png':
                 imagepng($targetImage, $cache_filename, 9, PNG_ALL_FILTERS);
                 break;
             case 'jpeg':
                 imagejpeg($targetImage, $cache_filename, 100);
                 break;
             case 'webp':
                 imagewebp($targetImage, $cache_filename);
                 break;
             case 'gif':
                 imagegif($targetImage, $cache_filename);
                 break;
         }
         imagedestroy($sourceImage);
         imagedestroy($targetImage);
     }
     return $cache_filename;
 }
Пример #15
0
 public function getRawFile($type, $quality = 100)
 {
     ob_start();
     switch ($type) {
         case Types::GIF:
             imagegif($this->resource);
             break;
         case Types::JPG:
             imagejpeg($this->resource, null, $quality);
             break;
         case Types::PNG:
             imagepng($this->resource);
             break;
         case Types::WEBP:
             imagewebp($this->resource);
             break;
     }
     $img = ob_get_clean();
     return $img;
 }
Пример #16
0
 /**
  * Prints the Image
  * 
  * @param string $name
  * @param string $directory
  * @param string $imageType
  */
 private function saveImage($name, $directory, $imageType = 'png', $foreground = null)
 {
     switch ($imageType) {
         case 'jpg':
         case 'jpeg':
             imagejpeg($this->imageProperties[0], $directory . DIRECTORY_SEPARATOR . $name . '.' . $imageType);
             break;
         case 'gif':
             imagegif($this->imageProperties[0], $directory . DIRECTORY_SEPARATOR . $name . '.' . $imageType);
             break;
         case 'gd':
             imagegd($this->imageProperties[0], $directory . DIRECTORY_SEPARATOR . $name . '.' . $imageType);
             break;
         case 'gd2':
             imagegd2($this->imageProperties[0], $directory . DIRECTORY_SEPARATOR . $name . '.' . $imageType);
             break;
         case 'webp':
             imagewebp($this->imageProperties[0], $directory . DIRECTORY_SEPARATOR . $name . '.' . $imageType);
             break;
         case 'wbmp':
             imagewbmp($this->imageProperties[0], $directory . DIRECTORY_SEPARATOR . $name . '.' . $imageType, $foreground);
             break;
         case 'xbm':
             imagexbm($this->imageProperties[0], $directory . DIRECTORY_SEPARATOR . $name . '.' . $imageType, $foreground);
             break;
         case 'svg':
         default:
             imagepng($this->imageProperties[0], $directory . DIRECTORY_SEPARATOR . $name . '.' . $imageType);
     }
     imagedestroy($this->imageProperties[0]);
 }
<?php

$image = imagecreate(1, 1);
// 1px image
$tempdir = sys_get_temp_dir() . '/php-gdtest';
if (!file_exists($tempdir) && !is_dir($tempdir)) {
    mkdir($tempdir, 0777, true);
}
$userinput = "1";
// from post or get data
$temp = $tempdir . "/test" . $userinput . ".tmp";
echo "\nimagewebp TEST\n";
imagewebp($image, $temp);
var_dump(file_exists($tempdir . "/test1"));
var_dump(file_exists($tempdir . "/test1.tmp"));
foreach (glob($tempdir . "/test*") as $file) {
    unlink($file);
}
Пример #18
0
 /**
  * Saves the image as WebP
  *
  * @param string $newFilePath
  *
  * @throws \BadFunctionCallException
  */
 public function saveAsWebP($newFilePath)
 {
     if (!file_exists('imagewebp')) {
         throw new \BadFunctionCallException("Storing images as WebP is not supported (you need to use PHP 5.5.)");
     }
     imagewebp($this->resource, $newFilePath);
 }
Пример #19
0
 /**
  * 输出图像
  * @access public
  * @param string $type 图像格式,可选:png,gif,jpg,wbmp,webp,xbm
  * 注意:webp需要php>=5.5
  */
 public function show($type = 'png')
 {
     switch ($type) {
         case 'png':
             imagepng($this->im);
             break;
         case 'gif':
             imagegif($this->im);
             break;
         case 'jpg':
             imagejpeg($this->im);
             break;
         case 'wbmp':
             imagewbmp($this->im);
             break;
         case 'webp':
             imagewebp($this->im);
             break;
         case 'xbm':
             imagexbm($this->im);
             break;
     }
 }
Пример #20
0
 /**
  * @param  string       $format
  * @param  resource     $resource
  * @param  mixed[]|null $options
  * @param  bool         $throw
  * @return string|false
  * @throws InvalidImageException
  */
 public function getContentsFromGdResource($format, $resource, array $options = [], $throw = false)
 {
     ob_start();
     switch ($format) {
         case PhpGdContext::FORMAT_WEBP:
             $success = @imagewebp($resource);
             break;
         case PhpGdContext::FORMAT_PNG:
             if (isset($options['png_compression'])) {
                 $compression = round($options['png_compression'] * 9 / 100);
             } else {
                 $compression = 9;
             }
             $success = @imagepng($resource, null, $compression, PNG_ALL_FILTERS);
             break;
         case PhpGdContext::FORMAT_JPEG:
             $quality = isset($options['jpeg_quality']) ? $options['jpeg_quality'] : 100;
             $success = @imagejpeg($resource, null, $quality);
             break;
         case PhpGdContext::FORMAT_GIF:
             if (!imageistruecolor($resource)) {
                 $resource = $this->getPalettizedGdResource($resource);
             }
             $success = @imagegif($resource);
             break;
         default:
             $success = false;
     }
     $contents = ob_get_clean();
     if (!$success && $throw) {
         throw new InvalidImageException('image.process.error');
     }
     return '' === $contents ? false : $contents;
 }
Пример #21
0
    public function resizeImage($output, $max_width = null, $max_height = null)
    {
        /***
         * Resize an image to parameters.
         *
         * @param string $output The path where the output will be
         *   saved.
         * @param int $max_width The maximum width of the resize, in
         *   pixels (aspect ratio will be maintained)
         * @param int $max_height The maximum height of the resize, in
         *   pixels (aspect ratio will be maintained)
         *
         * @return array An array containing:
         *  status: boolean
         *  error: Explanation (only if error)
         *  image_file: Original path (only if error)
         *  ouput: Path to resized image
         *  dimensions: Human-friendly new dimensions
         ***/
        if (!is_numeric($max_height)) {
            $max_height = 1000;
        }
        if (!is_numeric($max_width)) {
            $max_width = 2000;
        }
        if (function_exists(get_magic_quotes_gpc) && get_magic_quotes_gpc()) {
            $image = stripslashes($this->img);
        } else {
            $image = $this->img;
        }

        if (strrchr($image, '/')) {
            $filename = substr(strrchr($image, '/'), 1); # remove folder references
        } else {
            $filename = $image;
        }

        if (!file_exists($image)) {
            return array('status' => false,'error' => 'File does not exist','image_path' => $image);
        }

        $size = getimagesize($image);
        $width = $size[0];
        $height = $size[1];
        if ($width == 0) {
            return array('status' => false, 'error' => 'Unable to compute image dimensions','image_path' => $image);
        }
        # get the ratio needed
        $x_ratio = $max_width / $width;
        $y_ratio = $max_height / $height;

        # if image already meets criteria, load current values in
        # if not, use ratios to load new size info
        if (($width <= $max_width) && ($height <= $max_height)) {
            $tn_width = $width;
            $tn_height = $height;
        } elseif (($x_ratio * $height) < $max_height) {
            $tn_height = ceil($x_ratio * $height);
            $tn_width = $max_width;
        } else {
            $tn_width = ceil($y_ratio * $width);
            $tn_height = $max_height;
        }

        $resized = 'cache/'.$tn_width.'x'.$tn_height.'-'.$filename;
        $imageModified = @filemtime($image);
        $thumbModified = @filemtime($resized);

        # read image
        $ext = strtolower(substr(strrchr($image, '.'), 1)); # get the file extension
        switch ($ext) {
        case 'jpg':     # jpg
            $src = imagecreatefromjpeg($image) or self::notfound();
            break;
        case 'png':     # png
            $src = imagecreatefrompng($image) or self::notfound();
            break;
        case 'gif':     # gif
            $src = imagecreatefromgif($image) or self::notfound();
            break;
        case 'bmp':     # bmp
            $src = imagecreatefromwbmp($image) or self::notfound();
            break;
        case 'webp':     # webp
            $src = imagecreatefromwebp($image) or self::notfound();
            break;
        default:
            self::notfound();
        }

        # set up canvas
        $dst = imagecreatetruecolor($tn_width, $tn_height);

        imageantialias($dst, true);

        # copy resized image to new canvas
        imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);

        # send the header and new image
        if ($ext == 'jpg') {
            $status = imagejpeg($dst, $output, 75);
        } elseif ($ext == 'png') {
            $status = imagepng($dst, $output, 9);
        } elseif ($ext == 'gif') {
            $status = imagegif($dst, $output);
        } elseif ($ext == 'bmp') {
            $status = imagewbmp($dst, $output);
        } elseif ($ext == 'webp') {
            $status = imagewebp($dst, $output);
        } else {
            return array('status' => false,'error' => 'Illegal extension','image_path' => $image, 'extension' => $ext);
        }

        # clear out the resources
        imagedestroy($src);
        imagedestroy($dst);

        return array('status' => $status, 'output' => $output, 'output_size' => "$tn_width X $tn_height");
    }
Пример #22
0
 private function resize_with_gd($image_path, $save_as, $new_w, $new_h, $crop_w, $crop_h, $crop_x, $crop_y)
 {
     if ($this->is_webp($image_path)) {
         $mime = 'image/webp';
     } else {
         $info = getimagesize($image_path);
         if (!is_array($info)) {
             return false;
         }
         $image_w = $info[0];
         $image_h = $info[1];
         $mime = $info['mime'];
     }
     $crop = false;
     if ($crop_w != 0 && $crop_h != 0) {
         $crop = true;
     }
     if (function_exists('imagecreatetruecolor')) {
         $new_image = imagecreatetruecolor($new_w, $new_h);
         if ($crop) {
             $crop_image = imagecreatetruecolor($crop_w, $crop_h);
         }
     } else {
         $new_image = imagecreate($new_w, $new_h);
         if ($crop) {
             $crop_image = imagecreate($crop_w, $crop_h);
         }
     }
     $real_save_as = $save_as;
     $save_as = tempnam(PERCH_RESFILEPATH, '_gd_tmp_');
     switch ($mime) {
         case 'image/jpeg':
             $orig_image = imagecreatefromjpeg($image_path);
             if (function_exists('imagecopyresampled')) {
                 imagecopyresampled($new_image, $orig_image, 0, 0, 0, 0, $new_w, $new_h, $image_w, $image_h);
             } else {
                 imagecopyresized($new_image, $orig_image, 0, 0, 0, 0, $new_w, $new_h, $image_w, $image_h);
             }
             // sharpen
             if ($this->sharpening) {
                 $new_image = $this->sharpen_with_gd($new_image, $this->sharpening);
             }
             // progressive jpg?
             if ($this->progressive_jpeg) {
                 imageinterlace($new_image, 1);
             }
             if ($crop) {
                 imagecopy($crop_image, $new_image, 0, 0, $crop_x, $crop_y, $new_w, $new_h);
                 imagejpeg($crop_image, $save_as, $this->jpeg_quality);
             } else {
                 imagejpeg($new_image, $save_as, $this->jpeg_quality);
             }
             break;
         case 'image/gif':
             $orig_image = imagecreatefromgif($image_path);
             imagetruecolortopalette($new_image, true, 256);
             $new_image = $this->gd_set_transparency($new_image, $orig_image);
             if (function_exists('imagecopyresampled')) {
                 imagecopyresampled($new_image, $orig_image, 0, 0, 0, 0, $new_w, $new_h, $image_w, $image_h);
             } else {
                 imagecopyresized($new_image, $orig_image, 0, 0, 0, 0, $new_w, $new_h, $image_w, $image_h);
             }
             if ($crop) {
                 imagetruecolortopalette($crop_image, true, 256);
                 $crop_image = $this->gd_set_transparency($crop_image, $new_image);
                 imagecopy($crop_image, $new_image, 0, 0, $crop_x, $crop_y, $new_w, $new_h);
                 imagegif($crop_image, $save_as);
             } else {
                 imagegif($new_image, $save_as);
             }
             break;
         case 'image/png':
             $orig_image = imagecreatefrompng($image_path);
             imagealphablending($new_image, false);
             imagesavealpha($new_image, true);
             if (function_exists('imagecopyresampled')) {
                 imagecopyresampled($new_image, $orig_image, 0, 0, 0, 0, $new_w, $new_h, $image_w, $image_h);
             } else {
                 imagecopyresized($new_image, $orig_image, 0, 0, 0, 0, $new_w, $new_h, $image_w, $image_h);
             }
             // sharpen
             if ($this->sharpening) {
                 $colour = imagecolorat($new_image, 0, 0);
                 $new_image = $this->sharpen_with_gd($new_image, $this->sharpening);
                 imagesetpixel($new_image, 0, 0, $colour);
             }
             if ($crop) {
                 imagealphablending($crop_image, false);
                 imagesavealpha($crop_image, true);
                 imagecopy($crop_image, $new_image, 0, 0, $crop_x, $crop_y, $new_w, $new_h);
                 imagepng($crop_image, $save_as, $this->png_compression);
             } else {
                 imagepng($new_image, $save_as, $this->png_compression);
             }
             break;
         case 'image/webp':
             $orig_image = imagecreatefromwebp($image_path);
             $image_w = imagesx($orig_image);
             $image_h = imagesy($orig_image);
             imagealphablending($new_image, false);
             imagesavealpha($new_image, true);
             if (function_exists('imagecopyresampled')) {
                 imagecopyresampled($new_image, $orig_image, 0, 0, 0, 0, $new_w, $new_h, $image_w, $image_h);
             } else {
                 imagecopyresized($new_image, $orig_image, 0, 0, 0, 0, $new_w, $new_h, $image_w, $image_h);
             }
             // sharpen
             if ($this->sharpening) {
                 $colour = imagecolorat($new_image, 0, 0);
                 $new_image = $this->sharpen_with_gd($new_image, $this->sharpening);
                 imagesetpixel($new_image, 0, 0, $colour);
             }
             if ($crop) {
                 imagealphablending($crop_image, false);
                 imagesavealpha($crop_image, true);
                 imagecopy($crop_image, $new_image, 0, 0, $crop_x, $crop_y, $new_w, $new_h);
                 imagewebp($crop_image, $save_as);
             } else {
                 imagewebp($new_image, $save_as);
             }
             break;
         default:
             $orig_image = imagecreatefromjpeg($image_path);
             break;
     }
     imagedestroy($orig_image);
     imagedestroy($new_image);
     if ($crop) {
         imagedestroy($crop_image);
     }
     if (isset($orig_image)) {
         unset($orig_image);
     }
     if (isset($new_image)) {
         unset($new_image);
     }
     if (isset($crop_image)) {
         unset($crop_image);
     }
     copy($save_as, $real_save_as);
     unlink($save_as);
     return $mime;
 }
Пример #23
0
<?php

chdir(dirname(__FILE__));
require_once './RIFF.php';
function webp_read_metadata($filename)
{
    return WebP::createFromFile($filename)->getMetadata();
}
$im = imagecreatefrompng('Lenna.png');
imagewebp($im, 'Lenna.webp', WEBP_DEFAULT_QUALITY, $difference);
var_dump($difference);
$webp = WebP::createFromFile('Lenna.webp');
$webp->setComment('Lenna');
$webp->setCopyright('PLAYBOY');
$webp->dumpToFile('Lenna2.webp');
print_r(webp_read_metadata('Lenna2.webp'));
$im = imagecreatefromwebp('Lenna2.webp');
imagejpeg($im, 'Lenna.jpg');
Пример #24
0
 public function save($handle, $uri = null)
 {
     return imagewebp($handle, $uri);
 }
Пример #25
0
 /**
  * Get the image in a specific format
  * @param  string|null $format        optional format to get the image in, if null the source image format is used
  * @return string binary string of the converted image
  */
 public function getImage(string $format = null) : string
 {
     if (!$format) {
         $format = explode('/', $this->info['mime'], 2)[1];
     }
     switch (strtolower($format)) {
         case 'jpg':
         case 'jpeg':
             ob_start();
             imagejpeg($this->data);
             return ob_get_clean();
         case 'bitmap':
         case 'bmp':
             ob_start();
             imagewbmp($this->data);
             return ob_get_clean();
         case 'png':
             ob_start();
             imagepng($this->data);
             return ob_get_clean();
         case 'gif':
             ob_start();
             imagegif($this->data);
             return ob_get_clean();
         case 'webp':
             ob_start();
             imagewebp($this->data, null);
             return ob_get_clean();
         default:
             throw new ImageException('Unsupported format');
     }
 }