PHP使用imagick读取PDF生成png缩略图的两种方法

合集下载

使用PHP扩展php imagick对图片改变大小、旋转、锐化、减色或增加特效

使用PHP扩展php imagick对图片改变大小、旋转、锐化、减色或增加特效

使用PHP扩展php_imagick对图片改变大小、旋转、锐化、减色或增加特效php_imagick是PHP对图片处理的一个扩展包,可以完成对图片改变大小、旋转、锐化、减色或增加特效等操作。

一、windows下安装Imagick扩展:1、下载 ImageMagick并安装http://image_/image_magick/binaries/ImageMagick-6.6.2-10-Q16-windows -dll.exe2、下载php_imagick.dll/outside-blog-content/imagick-windows-builds/php53/imagick-2.3.0-dev/ vc9_nts/php_imagick.dll如果你用的是线程安全的php,请下载/outside-blog-content/imagick-windows-builds/php53/imagick-2.3.0-dev/vc9_zts/php_imagick.dll3、设置在php.ini中添加extension=php_imagick.dll ,重启web server二、linux下安装Imagick扩展:1.yum安装ImageMagickyum install ImageMagick ImageMagick-devel2.测试是否安装成功convert -version3.安装imagick扩展wget /get/imagick-3.1.0RC2.tgztar xzvf imagick-3.1.0RC2.tgzcd imagick-3.1.0RC2phpize./configuremakemake install4.编辑php.ini文件,在文件末尾添加如下代码extension=imagick.so5. 重新启动apache服务器service httpd restart三、案例1. 边框处理//by header('Content-type: image/jpeg');$image = new Imagick('test.jpg');$color=new ImagickPixel();$color->setColor("rgb(220,220,220)");$image->borderImage($color,5,4);$image->blurImage(5,5,imagick::CHANNEL_GREEN);echo $image;(PS:php Q扣峮:276167802,验证:wk)2.生成缩略图//by header('Content-type: image/jpeg');$image = new Imagick('test.jpg');$image->thumbnailImage(50, 0);echo $image;来源:清源教育。

利用PHP实现图片等比例放大和缩小的方法详解

利用PHP实现图片等比例放大和缩小的方法详解
$oldImg['w']=imagesx($img); $oldImg['h']=imagesy($img); if ($oldImg['w']<=$mySize['w'] && $oldImg['h']<156){ $rate=1; }elseif ($oldImg['w']>$mySize['w'] && $oldImg['h']<$mySize['h']){ $rate=$mySize['w']/$oldImg['w']; }elseif ($oldImg['w']<$mySize['w'] && $oldImg['h']>$mySize['h']){ $rate=$mySize['h']/$oldImg['h']; }elseif ($oldImg['w']>$mySize['w'] && $oldImg['h']>$mySize['h']){ $rate1=$mySize['w']/$oldImg['w']; $rate2=$mySize['h']/$oldImg['h']; if ($rate1>$rate2){$rate=$rate2;}else{$rate=$rate1;} } $newImg['w']=$oldImg['w']*$rate; $newImg['h']=$oldImg['h']*$rate; return "width=".$newImg['w']." height=".$newImg['h']; }

php生成图片缩略图功能示例

php生成图片缩略图功能示例

php生成图片缩略图功能示例php生成图片缩略图功能示例php生成图片缩略图功能,结合完整实例形式分析了php缩略图生成的详细步骤与相关实现技巧,需要的朋友可以参考下。

本文实例讲述了php生成图片缩略图功能。

分享给大家供大家参考,具体如下:完整代码如下(为方便阅读,代码使用/code/phpformat进行了格式化处理):<?php/** Created on 2011-3-18** To change the template for this generated file go to* Window - Preferences - PHPeclipse - PHP - Code Templates *//*构造函数-生成缩略图+水印,参数说明:$srcFile-图片文件名,$dstFile-另存文件名,$markwords-水印文字,$markimage-水印图片,$dstW-图片保存宽度,$dstH-图片保存高度,$rate-图片保存品质*/makethumb("1.jpg", "aa/b.jpg", "50", "50");function makethumb($srcFile, $dstFile, $dstW, $dstH, $rate = 100, $markwords = null, $markimage = null) {$data = GetImageSize($srcFile);switch ($data[2]) {case 1:$im = @ImageCreateFromGIF($srcFile); break;case 2:$im = @ImageCreateFromJPEG($srcFile); break;case 3:$im = @ImageCreateFromPNG($srcFile); break;}if (!$im) return False;$srcW = ImageSX($im);$srcH = ImageSY($im);。

Python将pdf转成图片的方法

Python将pdf转成图片的方法

Python将pdf转成图⽚的⽅法本篇⽂章记录如何使⽤python将pdf⽂件切分成⼀张⼀张图⽚,包括环境配置、版本兼容问题。

环境配置(mac)安装ImageMagickbrew install imagemagick这⾥有个坑,brew安装都是7.x版本,使⽤wand时会出错,需要你安装6.x版本。

解决办法:1.安装6.x版本brew install imagemagick@62.取消链接7.x版本brew unlink imagemagickUnlinking /usr/local/Cellar/imagemagick/7.0.7-4… 71 symlinks removed3.强制链接6.x版本brew link imagemagick@6 --forceLinking /usr/local/Cellar/imagemagick@6/6.9.9-15… 75 symlinks created4.export环境变量echo 'export PATH="/usr/local/opt/imagemagick@6/bin:$PATH"' >> ~/.bash_profileok,以上解决imagemagick版本问题。

安装gs必须安装gs,否则pdf⽆法转换。

brew install gs安装wandpip3 install wand我这⾥使⽤的是python3,所以需要⽤pip3.代码实现from wand.image import Imagedef convert_pdf_to_jpg(filename):with Image(filename=filename) as img :print('pages = ', len(img.sequence))with img.convert('jpeg') as converted:converted.save(filename='image/page.jpeg')效果笔者将⼀本书四百多页都转出来了,⼤家也可以去试下啦。

php生成缩略图的两种方法

php生成缩略图的两种方法

php生成缩略图的两种方法php生成缩略图的两种方法在php中如果要生成缩略图有什么办法呢?以下是店铺整理的两种方法,希望对大家有用,更多消息请关注应届毕业生网。

核心代码如下public function getImage(){// create instance$basePath = base_path('public/');$md5 = 'b8c3bf0b10a81c5b6a98c527868a0000';$sub1 = substr($md5, 0, 1);$sub2 = substr($md5, 1, 2);$subPath = sprintf("image/%s/%s/%s%s.jpg", $sub1, $sub2, $md5, '300x300');$sourcePath = sprintf("image/%s/%s/%s.jpg", $sub1, $sub2, $md5);//截成100x80的缩略图//$image = $this->getCropper($basePath.$sourcePath,$basePath.$subPath, 300, 300);$image = $this->getCrops($basePath.$sourcePath,$basePath.$subPath, 300, 300);}//生成缩略图function getCropper($source_path,$NewImagePath, $target_width, $target_height){$source_info = getimagesize($source_path);$source_width = $source_info[0];$source_height = $source_info[1];$source_mime = $source_info['mime'];$source_ratio = $source_height / $source_width; $target_ratio = $target_height / $target_width;// 源图过高if ($source_ratio > $target_ratio){$cropped_width = $source_width;$cropped_height = $source_width * $target_ratio; $source_x = 0;$source_y = ($source_height - $cropped_height) / 2; }// 源图过宽elseif ($source_ratio < $target_ratio){$cropped_width = $source_height / $target_ratio; $cropped_height = $source_height;$source_x = ($source_width - $cropped_width) / 2; $source_y = 0;}// 源图适中else{$cropped_width = $source_width;$cropped_height = $source_height;$source_x = 0;$source_y = 0;}switch ($source_mime){case 'image/gif':$source_image = imagecreatefromgif($source_path);break;case 'image/jpeg':$source_image = imagecreatefromjpeg($source_path);break;case 'image/png':$source_image = imagecreatefrompng($source_path);break;default:return false;break;}$target_image = imagecreatetruecolor($target_width, $target_height);$cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);// 图片裁剪imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height);// 图片缩放imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $cropped_width, $cropped_height);header('Content-Type: image/jpeg');imagejpeg($target_image,$NewImagePath,100);imagedestroy($source_image);imagedestroy($target_image);imagedestroy($cropped_image);}//生成缩略图,填充白边functiongetCrops($src_path,$NewImagePath,$width,$height){ //源图对象$src_image = imagecreatefromstring(file_get_contents($src_path));$source_info = getimagesize($src_path);$source_mime = $source_info['mime'];$src_width = imagesx($src_image);$src_height = imagesy($src_image);switch ($source_mime){case 'image/gif':$src_image = imagecreatefromgif($src_path);break;case 'image/jpeg':$src_image = imagecreatefromjpeg($src_path);break;case 'image/png':$src_image = imagecreatefrompng($src_path);break;default:return false;break;}//生成等比例的缩略图//$tmp_image_width = 0;//$tmp_image_height = 0;if ($src_width / $src_height >= $width / $height) {$tmp_image_width = $width;$tmp_image_height = round($tmp_image_width * $src_height / $src_width);} else {$tmp_image_height = $height;$tmp_image_width = round($tmp_image_height * $src_width / $src_height);}$tmpImage = imagecreatetruecolor($tmp_image_width, $tmp_image_height);imagecopyresampled($tmpImage, $src_image, 0, 0, 0, 0, $tmp_image_width, $tmp_image_height, $src_width, $src_height);//添加白边$final_image = imagecreatetruecolor($width, $height);$color = imagecolorallocate($final_image, 255, 255, 255);imagefill($final_image, 0, 0, $color);$x = round(($width - $tmp_image_width) / 2);$y = round(($height - $tmp_image_height) / 2);imagecopy($final_image, $tmpImage, $x, $y, 0, 0, $tmp_image_width, $tmp_image_height);//输出图片header('Content-Type: image/jpeg');imagejpeg($final_image,$NewImagePath,100);imagedestroy($src_image);imagedestroy($final_image);}。

PHP实现PDF转换成图片

PHP实现PDF转换成图片

PHP实现PDF转换成图⽚ImageMagick 是⼀个图象处理软件,也可以作为PHP的⼀个扩展来使⽤。

它可以编辑、显⽰包括JPEG、TIFF、PNM、PNG、GIF和Photo CS在内的绝⼤多数当今最流⾏的图象格式。

你可以改变图象尺⼨、旋转、锐化、减少颜⾊或加⼊特殊效果到图象⾥,并且能够以另⼀种图象格式保存。

同时,也可以实现将PDF转换为图⽚。

安装Imagick扩展安装步骤:《》配置ImageMagick修改/etc/ImageMagick-6/policy.xml,在</policymap>前新增⼀⾏:<policy domain="coder" rights="read | write" pattern="PDF" />实现$pdf = 'storage/test.pdf'; // PDF⽂件路径$path = 'storage'; // 图⽚存放⽬录$images = [];$imagick = new \Imagick();// 设置图⽚分辨率$imagick->setResolution(120, 120);// 该函数接受单个参数$quality,该参数保存⼀个表⽰图像压缩质量的整数值$imagick->setCompressionQuality(100);$imagick->readImage($pdf);foreach ($imagick as $key => $val) {// 设置图⽚格式并⽣成png图⽚$val->setImageFormat('png');$file = $path . DIRECTORY_SEPARATOR . md5($key.time()) . '.png'; if ($val->writeImage($file) === true) {$images[] = $file;}}。

生成缩略图

生成缩略图
4.新建一个画布图像imagecreatetruecolor($width,$height)
5.根据背景分配颜色sscanf()
6.为一幅图像分配颜色int imagecolorallocate ( resource $image , int $red , int $green , int $blue )
生成水印图片
首先获取原始图片信息getimagesize()(主要用来根据图片格式生成不同图片)
获取水印图片信息
根据图片信息的高和宽设置水印图片坐标
根据原始图片和水印图片信息获取资源 imagecreatefrompng imagecreatefromgif imagecratefromjpge
9生成缩略图
bool imagegif ( resource $image [, string $filename ] imagepng() imagejpge()
image由图象创建函数(例如imagecreatetruecolor())返回的图象资源。
filename文件保存的路径,如果未设置或为 NULL,将会直接输出原始图象流。
dst_image目标图象连接资源。
src_image源图象连接资源。
dst_x目标 X 坐标点。
dst_y目标 Y 坐标点。
src_x源的 X 坐标点。
src_y源的 Y 坐标点。
dst_w目标宽度。
dst_h目标高度。
src_w源图象的宽度。
src_h源图象的高度。
php生成缩略图的步骤
1.必须首先知道要生成缩略图的图片相关信息
getimagesize(image) //返回的是一个数组0 宽度 1高度 2图片信息是什么格式类型的

python自制PDF转换.PNG格式图片(按每页生成图片完整源码)小工具!

python自制PDF转换.PNG格式图片(按每页生成图片完整源码)小工具!

python自制PDF转换.PNG格式图片(按每页生成图片完整源码)小工具!使用PyQt5应用程序制作PDF转换成图片的小工具,可以导入PDF文档后一键生成对应的PNG图片。

PDF图片转换小工具使用的中间件:python版本:3.6.8UI应用版本:PyQt5PDF文件操作非标准库:PyPDF2PNG图片生成库:PyMuPDFpip install PyPDF2将需要使用到的python标准库或非标准库全部导入到我们的代码块中进入开发环节。

# Importing all the classes from the PyQt5.QtGui module.from PyQt5.QtGui import *# Importing all the classes from the PyQt5.QtCore module.from PyQt5.QtCore import *# Importing all the classes from the PyQt5.QtWidgets modu le.from PyQt5.QtWidgets import *# Importing the `fitz` module.import fitz# Importing the PyPDF2 module.import PyPDF2# Importing the `sys` module.import sys# Importing the os module.import os# Importing the traceback module.import traceback接下来直接进入正题,首先创建名称为PdfToPngUI的python类,将UI组件及布局和相关的槽函数都写入到这个类中。

# This class is a widget that contains a button and a text bo x. When the button is clicked, the text box is populated with # the path to the converted fileclass PdfToPngUI(QWidget):def__init__(self):"""A constructor. It is called when an object is created from a cl ass and it allows the class to initialize theattributes of a class."""super(PdfT oPngUI, self).__init__()self.init_ui()def init_ui(self):"""This function initializes the UI."""self.setWindowTitle('PDF图片转换工具公众号:Python 集中营')self.setWindowIcon(QIcon('analysis.ico'))self.resize(600, 400)self.source_pdf_path = QLineEdit()self.source_pdf_path.setPlaceholderText('PDF文件路径')self.source_pdf_path.setReadOnly(True)self.source_pdf_btn = QPushButton()self.source_pdf_btn.setText('导入')self.source_pdf_btn.clicked.connect(self.source_pdf_btn_click)self.target_png_path = QLineEdit()self.target_png_path.setPlaceholderText('目标图片存储路径') self.target_png_path.setReadOnly(True)self.target_png_btn = QPushButton()self.target_png_btn.setText('路径')self.target_png_btn.clicked.connect(self.target_png_btn_click)self.start_btn = QPushButton()self.start_btn.setText('PDF一键生成PNG图片')self.start_btn.clicked.connect(self.start_btn_click)self.brower = QTextBrowser()self.brower.setReadOnly(True)self.brower.setFont(QFont('宋体', 8))self.brower.setPlaceholderText('日志处理过程区域...')self.brower.ensureCursorVisible()grid = QGridLayout()grid.addWidget(self.source_pdf_path, 0, 0, 1, 2) grid.addWidget(self.source_pdf_btn, 0, 2, 1, 1) grid.addWidget(self.target_png_path, 1, 0, 1, 2) grid.addWidget(self.target_png_btn, 1, 2, 1, 1) grid.addWidget(self.start_btn, 2, 0, 1, 3)grid.addWidget(self.brower, 3, 0, 1, 3)self.pdf_thread = WorkThread(self)self.pdf_thread.message.connect(self.show_message) self.pdf_thread.finished.connect(self.finished)self.setLayout(grid)def show_message(self, text):"""It shows a message:param text: The text to be displayed"""cursor = self.brower.textCursor()cursor.movePosition(QTextCursor.End)self.brower.append(text)self.brower.setTextCursor(cursor)self.brower.ensureCursorVisible()def source_pdf_btn_click(self):"""It opens a file dialog box to select the source PDF file."""source_pdf_path = QFileDialog.getOpenFileName(self, "选取文件", os.getcwd(), "PDF File (*.pdf)")self.source_pdf_path.setText(source_pdf_path[0])def target_png_btn_click(self):"""A function that is called when the target_png_btn is clicked."""target_png_path = QFileDialog.getExistingDirectory(self, '选择文件夹', os.getcwd())self.target_png_path.setText(target_png_path)def start_btn_click(self):"""A function that is called when the start button is clicked."""self.pdf_thread.start()self.start_btn.setEnabled(False)def finished(self, finished):"""A function that is called when the target_png_btn is clicked"""if finished is True:self.start_btn.setEnabled(True)通过上面的PdfToPngUI类处理,这个时候UI组件及布局和槽函数已经开发完成了,应用的页面效果如下。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

这篇文章主要介绍了PHP使用imagick读取PDF第一页生成png缩略图的两种方法,使用了PHP扩展php_imagick,需要的朋友可以参考下
一、ImageMagick是什么
ImageMagick是一套功能强大、稳定而且免费的工具集和开发包,可以用来读、写和处理超过185种基本格式的图片文件,包括流行的TIFF, JPEG, GIF, PNG, PDF以及PhotoCD 等格式。

利用ImageMagick,你可以根据web应用程序的需要动态生成图片, 还可以对一个(或一组)图片进行改变大小、旋转、锐化、减色或增加特效等操作,并将操作的结果以相同格式或其它格式保存。

二、php_imagick什么
一个可以供PHP调用ImageMagick功能的PHP扩展。

使用这个扩展可以使PHP具备和ImageMagick相同的功能。

三、PDF生成png缩略图的两种方法
第一种:
代码如下:/**
* PDF2PNG
* @param $pdf 待处理的PDF文件
* @param $path 待保存的图片路径
* @param $page 待导出的页面-1为全部0为第一页1为第二页
* @return 保存好的图片路径和文件名
*/
function pdf2png($pdf,$path,$page=0)
{
if(!is_dir($path))
{
mkdir($path,true);
}
if(!extension_loaded('imagick'))
{
echo '没有找到imagick!' ;
return false;
}
if(!file_exists($pdf))
{
echo '没有找到pdf' ;
return false;
}
$im = new Imagick();
$im-&gt;setResolution(120,120); //设置图像分辨率
$im-&gt;setCompressionQuality(80); //压缩比
$im-&gt;readImage($pdf."[".$page."]"); //设置读取pdf的第一页
//$im-&gt;thumbnailImage(200, 100, true); // 改变图像的大小
$im-&gt;scaleImage(200,100,true); //缩放大小图像
$filename = $path."/". time().'.png';
if($im-&gt;writeImage($filename) == true)
{
$Return = $filename;
}
return $Return;
}
$s = pdf2png('file/1371273225-ceshi_ppt.pdf','images');
echo '&lt;div align="center"&gt;&lt;img src="'.$s.'"&gt;&lt;/div&gt;'; 第二种:
代码如下:function pdf2png($PDF,$Path){
if(!extension_loaded('imagick')){
return false;
}
if(!file_exists($PDF)){
return false;
}
$IM = new imagick();
$IM-&gt;setResolution(120,120);
$IM-&gt;setCompressionQuality(100);
$IM-&gt;readImage($PDF);
foreach ($IM as $Key =&gt; $Var){
$Var-&gt;setImageFormat('png');
$Filename = $Path.'/'.md5($Key.time()).'.png';
if($Var-&gt;writeImage($Filename) == true){
$Return[] = $Filename;
}
}
return $Return;
}
更多信息请查看IT技术专栏。

相关文档
最新文档