[PHP+ImageMagick] Convert PDF to image (detailed steps)
ImageMagick installation
ImageMagick is a free software for creating, editing, and synthesizing pictures. It can read, convert, and write images in multiple formats. Picture cutting, color replacement, application of various effects, picture rotation, combination, text, straight lines, polygons, ellipses, curves, extension and rotation attached to pictures. ImageMagick is free software: all source code is open and can be used, copied, modified, and distributed freely. It complies with the GPL license agreement and can run on most operating systems. Most of the functions of ImageMagick come from command line tools.
To use ImageMagick in PHP, you need to install the imagick
extension. imagick
is similar to the gd
extension and is mainly used for image processing. But imagick
is more powerful. The following is a brief introduction to the installation methods of imagick
in two common environments.
Installation in CentOS 7
You can use Yum
to install directly in CentOS. In addition to installing ImageMagick
, you also need to Install its two dependencies ImageMagick-devel
and ImageMagick-perl
.
yum install -y ImageMagick ImageMagick-devel ImageMagick-perl
Then use pecl
to install the extension. Find pecl
in the PHP installation directory. For example, PHP is installed in the /usr/local/php74
directory, then pecl
is usually in /usr/local /php74/bin
In the target, execute the command:
/usr/local/php74/bin/pecl install imagick
to use pecl
to automatically download and install ImageMagick
, and finally in php.ini Add
extension=imagick.so
to enable the extension.
If you need to check whether the extension is installed successfully, you can execute the command
php -m|grep imagick
If imagick
is output, it means the extension is installed successfully.
Digression: If you don’t know which php.ini
configuration file PHP uses, you can execute the following command
php74 -i|grep ini
Find the line "Loaded Configuration File" and you will know which configuration file PHP uses. The php -i
command
is similar to the function we use phpinfo()
to view PHP related information.
Docker installation
To install extensions for PHP in the container, it is recommended to use docker-php-extension-installer on Github. This is a Shell script that can Help us solve the extension dependency problem, and automatically clear useless files after installing the extension. We only need to add this script to the Dockerfile. The following is the official example:
FROM php:7.2-cli # 从Github上下载docker-php-extension-installer脚本 ADD https://github.com/mlocati/docker-php-extension-installer/releases/latest/download/install-php-extensions /usr/local/bin/ # 添加可执行权限并安装扩展 RUN chmod +x /usr/local/bin/install-php-extensions && \ install-php-extensions gd xdebug imagick
The image built in this way will have the required extensions installed.
Digression: In the domestic network environment, timeout problems often occur when using docker-php-extension-installer
to install extensions. It is recommended to use the external network. Build the image on your VPS, upload it to DockerHub or other private warehouses, and then pull it to the local network for use. You can use a cheap conscience cloud, or a VPS like Vultr that supports time-based billing.
PDF to image
Code example:
// 实例化imagick对象 $im = new imagick(); $im->setResolution(150, 150); $im->setCompressionQuality(100); $im->readImageBlob($fileContent); $im->setImageFormat('jpg'); $im->setImageBackgroundColor('white'); $im->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE); $im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN); header("Content-type: image/jpeg"); echo $im->getImageBlob();
Code interpretation:
$im->setResolution(150, 150);
Used to set the resolution of the image. This function does not change the actual resolution of the image, it just sets it in the Imagick object before reading or creating the image. This function needs to be called before reading the image or creating the image.
This function receives two parameters, namely horizontal resolution and vertical resolution. The default value is 72*72. In order to maintain the aspect ratio of the image, the values of these two parameters should be the same. The image converted by the default value is not clear enough. It is recommended to use double or triple the value, but the size of the image will also become larger.
$im->setCompressionQuality(100);
Set the compression quality of the image. The default value is 0; the parameter value passed in should be 1-100. For JPG format pictures, the smaller the value, the smaller the image volume and the sharpness. Lower; but for PNG images, this conclusion does not seem to hold. When the value is less than 90, the image size will be larger, so when converting to PNG image format, just keep the default value.
$im->readImageBlob($fileContent);
Directly load the binary content of the PDF file, or you can use the readImage($filename)
function to read the saved PDF file.
$im->setImageFormat('jpg');
Set the format of the image to be generated, such as jpg
,png
, etc.,
$im->setImageBackgroundColor('white'); $im->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE); $im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
Set the image background color is white, remove the alpha channel of the image, and merge all images into one layer. If you do not perform these operations, the background of the converted image will be black, as shown below:
header("Content-type: image/png"); echo $im->getImageBlob();
获取转换生成图像的二进制数据,输出到客户端供下载;如果需要保存到文件,可以使用writeImage($filename)
函数。
推荐:《PHP视频教程》
The above is the detailed content of [PHP+ImageMagick] Convert PDF to image (detailed steps). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.
