Php imagick convert to webp

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

php convert images to webp format

License

vuatintac/php-image-to-webp-convert

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

php image to webp convert

php convert images to webp format

php function convert image to webp

/** * Generate Webp image format * https://www.jclabs.co.uk/generate-webp-images-in-php-using-and-gd-or-imagick/ * Uses either Imagick or imagewebp to generate webp image * * @param string $file Path to image being converted. * @param int $compression_quality Quality ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). * * @return false|string Returns path to generated webp image, otherwise returns false. */ function webpConvert($file, $compression_quality = 80) < // check if file exists if (!file_exists($file)) < return false; > $file_type = strtolower(pathinfo($file, PATHINFO_EXTENSION)); $output_file = $file . '.webp'; if (file_exists($output_file)) < return $output_file; > if (function_exists('imagewebp')) < switch ($file_type) < case 'jpeg': case 'jpg': $image = imagecreatefromjpeg($file); break; //(PHP 8 >= 8.1.0) // case 'avif': // $image = imagecreatefromavif($file); // break; case 'bmp': $image = imagecreatefrombmp($file); break; case 'xbm': $image = imagecreatefromxbm($file); break; case 'png': $image = imagecreatefrompng($file); imagepalettetotruecolor($image); imagealphablending($image, true); imagesavealpha($image, true); break; case 'gif': $image = imagecreatefromgif($file); break; default: return false; > // Save the image $result = imagewebp($image, $output_file, $compression_quality); if (false === $result) < return false; > // Free up memory imagedestroy($image); return $output_file; > elseif (class_exists('Imagick')) < $image = new Imagick(); $image->readImage($file); if ($file_type === 'png') < $image->setImageFormat('webp'); $image->setImageCompressionQuality($compression_quality); $image->setOption('webp:lossless', 'true'); > $image->writeImage($output_file); return $output_file; > return false; >

use code php convert image to webp :

Читайте также:  Udemy python jose portilla

$file ="images.jpg"; $newfile ="images.jpg.webp"; // nếu file ko tồn tại và file name nhỏ hơn 0 if(!file_exists($newfile) || filesize($newfile)==0)< $newfile = webpConvert($file); header('Content-type:image/webp'); header('Cache-Control:public, max-age=315360000'); echo file_get_contents($newfile); die; >else< echo "file invalid format. bla bla. "; die; >

Источник

WebP Support with ImageMagick and PHP

Key art image for WebP Support with ImageMagick and PHP

I’ve been wanting to get WebP set-up on my site for a little while now, the biggest barrier to entry has been getting it integrated into the flow already had, where I generate different sized images where I need to.

It turns out you can use ImageMagick if it can find libwebp-dev when it’s built.

By default, unfortunately, Ubuntu doesn’t come with ImageMagick built with WebP support and I’m assuming the same is true for Debian (I got everything working on Ubuntu and went through the same process on Debian — didn’t check Debian needed this, I just assumed).

Anyway, I stumbled on this post which outlines how you can build webp support into ImageMagick.

Check Your Version

After landing WebP I ended up hitting a problem later on where the alpha channel was messed up somewhere in the WebP conversion and displayed a black background — Booooo.

The way to get around the problem is to install a version higher than or equal to 6.8.3-0 Beta. This may be an option for you using the information on this ImageMagick post. The problem here, is that to compile newer versions of ImageMagick you need to have version 0.3.0 or higher of libwebp. Debian (and possibly) Ubuntu ships with 0.1.3. You can check yours with:

What to do? Well I bailed at this point. The code is sat on my server, but disabled by a boolean. When I get a newer version of ImageMagick or libwebp I will update everything and see if enabling it works or not.

Adding WebP Support to ImageMagick

To support WebP conversion in ImageMagick I had to install libwebp-dev with:

Then it was a case of rebuilding ImageMagick.

This all seemed to work, although I did get some weird/scary looking error messages after the final command.

What I ended up doing to get around this was run the following:

Web Page Test

I ran everything through WebPageTest.org and WebP has a positive impact on my site (surprise, surprise).

On the home page the image went from 141.5 KB to 66.8 KB and that results in a load time from 959 ms to 393 ms.

Читайте также:  Failed opening required wp settings php

You can see the difference in the results below.

How Do You Convert to WebP?

One thing I do on my site is format the file names in the URL in such a way that it includes the desired image dimensions as well as the density of the screen.

This means I can decide what size image I send to the browser.

For that reason, I got ImageMagick to do a couple of extra things, other than just convert, it strips the images metadata, crops it and then resizes it.

getImageGeometry(); $origImgWidth = $origImageDimens['width']; $origImgHeight = $origImageDimens['height']; if($newWidth == 0) < $ratioOfHeight = $newHeight / $origImgHeight; $newWidth = $origImgWidth * $ratioOfHeight; >if($newHeight == 0) < $ratioOfWidth = $newWidth / $origImgWidth; $newHeight = $origImgHeight * $ratioOfWidth; >$widthRatios = $origImgWidth / $newWidth; $heightRatios = $origImgHeight / $newHeight; if($widthRatios else < $cropWidth = $newHeight * $heightRatios; $cropHeight = $origImgHeight; >$cropX = ($origImgWidth - $cropWidth) / 2; $cropY = ($origImgHeight - $cropHeight) / 2; $image->stripImage(); $image->cropImage($cropWidth, $cropHeight, $cropX, $cropY); $image->resizeImage($newWidth, $newHeight, imagick::FILTER_LANCZOS, 0.9); $image->setImageFormat('webp'); $image->setImageAlphaChannel(imagick::ALPHACHANNEL_ACTIVATE); $image->setBackgroundColor(new ImagickPixel('transparent')); $image->writeImage($resizedFilepath); > 

The important lines of code for WebP conversion are:

This defines the final image format to WebP and then ensures that if you are converting a PNG, it keeps any alpha channels.

Apache GD Method for WebP Conversion

The Apache GD library can actually handle WebP as well and this was going to be my original approach, however some issues in the library caused it to incorrectly pad the file so it fails to render.

If that wasn’t an issue, the basic code would look something like:

imageCreateFromAny($originalFilepath); if(!$im) < // Unrecognized format return false; >imagewebp($im, $resizedFilepath); imagedestroy($im); 

Where imageCreateFromAny is a method I found from this PHP Doc.

Detecting WebP Support or Not

Browsers which support WebP will include an accept header for ‘image/webp’ which I just look for and take that as a go ahead to serve up WebP.

= 0); if($webpsupport) < $this->attemptToServeWebP($pathinfo, $matches, $width, $height, $density); > else < $this->attemptToServeNormal($pathinfo, $matches, $width, $height, $density); > 

Useful Tid-Bit

If you need to delete all of your auto generated WebP files for some reason, this will delete all of them from your current directory (including sub-directories).

Conclusion

WebP is pretty cool for shaving off some extra page weight and it’s not too bad to support if you have some kind of image generation in place already.

If not, then it may be worth looking for a Grunt or Gulp task to do it.

Found this post helpful?

If you found this helpful and would like to support me, please consider buying me a coffee. Any help goes a long way to help me prioritize and maintain this site and my projects.

Источник

Legacy ImageMagick Discussions Archive

Use https://github.com/ImageMagick/ImageMagick/discussions instead.

Converting image to webp with ImageMagick

Questions and postings pertaining to the usage of ImageMagick regardless of the interface. This includes the command-line utilities, as well as the C and C++ APIs. Usage questions are like «How do I use ImageMagick to create drop shadows?».

Читайте также:  Upload new File

dal77 Posts: 1 Joined: 2016-10-23T03:52:41-07:00 Authentication code: 1151

Converting image to webp with ImageMagick

Post by dal77 » 2016-10-23T04:08:05-07:00

I am trying to to convert a jpg image to webp in a php script that uses Imagick, but it fails to recognise the webp format. I have installed the latest version of ImageMagick from source, libwebp-dev and php-imagick. I cannot figure out what I am missing.

$im = new Imagick('$src'); $im->resizeImage($width,$height,Imagick::FILTER_CATROM , 1,TRUE ); $im->setImageFormat( "webp" ); PHP Fatal error: Uncaught ImagickException: Unable to set image format in /ImageMagick-7.0.3-4/test.php:15 Stack trace: #0 /ImageMagick-7.0.3-4/test.php(15): Imagick->setimageformat('webp') #1

Version: ImageMagick 7.0.3-4 Q16 x86_64 2016-10-23 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2016 ImageMagick Studio LLC
License: http://www.imagemagick.org/script/license.php
Features: Cipher DPC HDRI OpenMP
Delegates (built-in): jbig jpeg tiff webp

imagick
imagick module => enabled
imagick module version => 3.4.2
imagick classes => Imagick, ImagickDraw, ImagickPixel, ImagickPixelIterator, ImagickKernel
Imagick compiled with ImageMagick version => ImageMagick 6.8.9-9 Q16 x86_64 2016-04-18 http://www.imagemagick.org
Imagick using ImageMagick library version => ImageMagick 6.8.9-9 Q16 x86_64 2016-06-01 http://www.imagemagick.org
ImageMagick copyright => Copyright (C) 1999-2014 ImageMagick Studio LLC
ImageMagick release date => 2016-06-01
ImageMagick number of supported formats: => 215
ImageMagick supported formats => 3FR, AAI, AI, ART, ARW, AVI, AVS, BGR, BGRA, BIE, BMP, BMP2, BMP3, BRF, CAL, CALS, CANVAS, CAPTION, CIN, CIP, CLIP, CMYK, CMYKA, CR2, CRW, CUR, CUT, DCM, DCR, DCX, DDS, DFONT, DJVU, DNG, DOT, DPX, DXT1, DXT5, EPDF, EPI, EPS, EPS2, EPS3, EPSF, EPSI, EPT, EPT2, EPT3, ERF, EXR, FAX, FITS, FRACTAL, FTS, G3, GIF, GIF87, GRADIENT, GRAY, GROUP4, GV, HALD, HDR, HISTOGRAM, HRZ, HTM, HTML, ICB, ICO, ICON, INFO, INLINE, IPL, ISOBRL, JBG, JBIG, JNG, JNX, JPEG, JPG, JSON, K25, KDC, LABEL, M2V, M4V, MAC, MAP, MASK, MAT, MATTE, MEF, MIFF, MNG, MONO, MOV, MP4, MPC, MPEG, MPG, MRW, MSL, MSVG, MTV, MVG, NEF, NRW, NULL, ORF, OTB, OTF, PAL, PALM, PAM, PANGO, PATTERN, PBM, PCD, PCDS, PCL, PCT, PCX, PDB, PDF, PDFA, PEF, PES, PFA, PFB, PFM, PGM, PICON, PICT, PIX, PJPEG, PLASMA, PNG, PNG00, PNG24, PNG32, PNG48, PNG64, PNG8, PNM, PPM, PREVIEW, PS, PS2, PS3, PSB, PSD, PTIF, PWP, RADIAL-GRADIENT, RAF, RAS, RAW, RGB, RGBA, RGBO, RGF, RLA, RLE, RMF, RW2, SCR, SCT, SFW, SGI, SHTML, SIX, SIXEL, SPARSE-COLOR, SR2, SRF, STEGANO, SUN, SVG, SVGZ, TEXT, TGA, THUMBNAIL, TIFF, TIFF64, TILE, TIM, TTC, TTF, TXT, UBRL, UIL, UYVY, VDA, VICAR, VID, VIFF, VIPS, VST, WBMP, WMF, WMV, WMZ, WPG, X, X3F, XBM, XC, XCF, XPM, XPS, XV, XWD, YCbCr, YCbCrA, YUV

snibgo Posts: 12159 Joined: 2010-01-23T23:01:33-07:00 Authentication code: 1151 Location: England, UK

Re: Converting image to webp with ImageMagick

Post by snibgo » 2016-10-23T06:01:08-07:00

As you are using Imagick, the question is whether the ImageMagick library it uses has been built with webp.

You have another installatation, 7.0.3-4 with webp, but that isn’t relevant.

Источник

Оцените статью