Imagick
| Language | PHP (C extension) |
|---|---|
| License | PHP License 3.01 (ImageMagick license for ImageMagick) |
| Repository | github.com/Imagick/imagick |
| Documentation | php.net/imagick, ImageMagick JP2 options |
| Depends on | ImageMagick built with OpenJPEG |
| Read / write | yes / yes; JP2, J2K, J2C, JPC (formats JP2, J2K, J2C, JPC) |
Imagick is the PHP binding of ImageMagick. ImageMagick uses OpenJPEG for JPEG 2000, so whether Imagick can open .jp2 files depends on how your ImageMagick was built; Linux distribution packages, Homebrew and the official Windows builds include it.
JPEG 2000 options such as the reduce factor and the number of quality layers are passed as ImageMagick “defines” with setOption before reading.
Installation#
Shell
# Debian / Ubuntu
sudo apt install php-imagick
# macOS (Homebrew PHP)
brew install imagemagick
pecl install imagick
Check JPEG 2000 support:
PHP
<?php
var_dump(in_array('JP2', Imagick::queryFormats('JP2'))); // bool(true)
Basic usage: convert JPEG 2000 to JPEG#
PHP
<?php
$im = new Imagick('in.jp2');
printf("%d x %d, depth %d\n", $im->getImageWidth(), $im->getImageHeight(), $im->getImageDepth());
$im->setImageFormat('jpeg');
$im->setImageCompressionQuality(85);
$im->writeImage('out.jpg');
$im->clear();
How to save JPEG 2000#
setImageCompressionQuality controls the compression; 100 is lossless:
PHP
<?php
$im = new Imagick('in.png');
$im->setImageFormat('jp2'); // 'j2k' for a raw codestream
$im->setImageCompressionQuality(40); // lossy
$im->writeImage('out.jp2');
$im->setImageCompressionQuality(100); // lossless
$im->writeImage('lossless.jp2');
How to decode at reduced resolution#
Set the jp2:reduce-factor define before reading. Each step halves width and height and makes decoding much faster for large files:
PHP
<?php
$im = new Imagick();
$im->setOption('jp2:reduce-factor', '3'); // 1/8 size
$im->setOption('jp2:quality-layers', '1'); // first quality layer only
$im->readImage('big.jp2');
$im->writeImage('preview.png');
How to make a thumbnail#
PHP
<?php
$im = new Imagick();
$im->setOption('jp2:reduce-factor', '2');
$im->readImage('scan.jp2');
$im->thumbnailImage(300, 0); // 300 px wide, keep aspect ratio
$im->setImageFormat('webp');
$im->writeImage('thumb.webp');
Tips#
pingImage('in.jp2')reads only the header; use it to get the size of large files before decoding.- Set resource limits (
Imagick::setResourceLimit(Imagick::RESOURCETYPE_MEMORY, ...)) when decoding big satellite or scanned images.