A PHP wrapper for lovell/sharp, a high performance Node.js image processing library.
Common use cases:
- Resize image
- Convert image format
For more information on Sharp, see the official documentation here.
Install node in your system. Installation of node is very simple.
Check if you have node installed:
node -v
The command should display the version number.
Install the packages at the root of your PHP project:
composer require kiatng/php-sharp
npm install sharp
This last command will create a node_modules
directory, package-lock.json
and package.json
.
- PHP >= 7.4
- Node.js and npm (for Sharp installation)
- Sharp npm package
There is only one static method run
in the Sharp
class. It takes two arguments:
$io
: Input and output parameters$params
: Parameters for the image processing
Refer to the Sharp documentation on the specifications of the parameters.
Convert SVG to PNG and resize the image:
use KiatNg\Sharp;
$png = Sharp::run(
[
'input' => ['is_raw' => true, 'data' => $svg, 'ext' => 'svg'],
'output' => ['is_raw' => true],
],
[
'toFormat' => ['format' => 'png'], // Required for raw output
'resize' => ['width' => 300, 'height' => 200]
]
); // Returns a raw PNG binary string
is_raw
is a boolean parameter that indicates if the input is a raw data or a file path.
$svg
is the raw SVG XML string.
ext
is the image format: jpg, png, svg of the source data; it's used as the file extension internally.
Example with file paths including filename and extension:
Sharp::run(
[
'input' => ['is_raw' => false, 'data' => $svgPath],
'output' => ['is_raw' => false, 'file' => $pngPath],
],
[
//'toFormat' => ['format' => 'png'], Not required if $pngPath has .png extension
'resize' => ['width' => 300, 'height' => 200]
]
);
Refer to the test cases in tests/Unit/SharpTest.php
for more examples.
Contributions are welcome! Here's how you can help:
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Install dependencies:
composer install
npm install
- Make your changes and add your feature
- Write or update tests for your changes if applicable
- Run tests to ensure everything works:
composer test
- Commit your changes (
git commit -m 'Add some amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!
- Follow PSR-12 coding standards
- Add tests for new features
- Update documentation as needed
This project is licensed under the MIT License - see the LICENSE file for details.
This project was inspired by choowx/rasterize-svg.