search
HomeBackend DevelopmentPHP Tutorial[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

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:

[PHP+ImageMagick] Convert PDF to image (detailed steps)


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!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment