Home >Backend Development >PHP Tutorial >How to use ImageMagick to generate base64 images in php (code)
The content of this article is about how to use ImageMagick to generate base64 images (code) in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
In recent PHP projects, drawing and picture splicing effects need to be used. Here are some points used in the development process and some pitfalls that have been encountered. Generate base64 image format through ImageMagick for use by the front end.
Some required knowledge points
PHP converts images to base64 encoding and converts base64 images to images and saves the code
Convert images to base64 encoding
/*图片转换为 base64格式编码*/ $img = 'uploads/about.png'; $base64_img = base64EncodeImage($img); echo '<img alt="How to use ImageMagick to generate base64 images in php (code)" >'; function base64EncodeImage ($image_file) { $base64_image = ''; $image_info = getimagesize($image_file); $image_data = fread(fopen($image_file, 'r'), filesize($image_file)); $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data)); return $base64_image; }
base64 pictures are converted to pictures and saved
/* base64格式编码转换为图片并保存对应文件夹 */ function base64_image_content($base64_image_content,$path){ //匹配出图片的格式 if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){ $type = $result[2]; $new_file = $path."/".date('Ymd',time())."/"; if(!file_exists($new_file)){ //检查是否有该文件夹,如果没有就创建,并给予最高权限 mkdir($new_file, 0700); } $new_file = $new_file.time().".{$type}"; if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){ return '/'.$new_file; }else{ return false; } }else{ return false; } } echo base64_image_content($base64_img,"uploads/");
base64
Base64 is a method of representing arbitrary binary data using 64 characters.
The principle of Base64 is very simple. First, prepare an array containing 64 characters:
['A', 'B', 'C', ... 'a', ' b', 'c', ... '0', '1', ... ' ', '/']
Then, the binary data is processed, each group of 3 bytes, The total is 3x8=24bit, divided into 4 groups, each group has exactly 6 bits
What if the binary data to be encoded is not a multiple of 3, and there will be 1 or 2 bytes left in the end? After Base64 pads the end with x00 bytes, then adds 1 or 2 = signs at the end of the encoding to indicate how many bytes are padded, which will be automatically removed during decoding.
Use jpg pictures to be smaller than png
Use PHP's Imagick class to operate images
Imagick specific operations
(1). Create a base map, A picture with a width of 750px, a height of 1046px, a white background, and a jpg format
// 初始化一个画板 $img =new Imagick(); $img->newImage(750,1046,'white','jpg') ;
(2). Add the required picture to the base map
provided that we already know the link address of the picture that needs to be merged
$item_img='https://img.alicdn.com/bao/uploaded/i1/1750208593/TB1rgM3hhtnkeRjSZSgXXXAuXXa_!!0-item_pic.jpg' 第一步:实例化图片 $imgtwo = new Imagick($item_img); 第二步:设置添加图片的大小 $imgtwo->resizeImage(750,764,Imagick::FILTER_LANCZOS,1); 关于resizeImage参数说明 bool Imagick::resizeImage ( int $columns , int $rows , int $filter , float $blur [, bool $bestfit = false ] ) 参数: ● columns 图片的宽度 ● rows 图片高度 ● filter 过滤器,用于过滤图片,有高斯filte根据情况而定 ● blur blur=1 为虚化, blur =-1 为锐化 第三步:与底图合并 $img->compositeImage($imgtwo,$imgtwo->getImageCompose(),0,0); 使用compositeImage(); bool Imagick::compositeImage ( Imagick $composite_object , int $composite , int $x , int $y [, int $channel = Imagick::CHANNEL_ALL ] ) 参数: ● composite_object :用于合并的图片的Imagick对象 ● composite:合并操作,定义操作常量。 具体请查看 合并操作常量列表 ● x:相对图像顶点左上位置(0,0)的横坐标 ● y:相对图像顶点左上位置(0,0)的纵坐标 ● channel:通过传入一个通道常量,来开启通道模式。为了支持多个通道,可以通过二进制运算的操作来合并多个通道常量。 到这里就可以得到一个合并的图片了 1、加一个header信息,可以直接在网页上查看图片 header("Content-Type: img/png"); echo $img; 2、可以把图片在指定目录中生成,在指定目录下生成为img.png $file="./img.png"; $img->writeImage($file); 我这里是这样处理: header ( 'Content-type: ' . strtolower ($img->getImageFormat ()) ); $type = strtolower($img->getImageFormat()); $dest_img='/data/tmp/' . md5(microtime(true)).'.'.$type; //要生成的图片的路径,随机生成图片名称
(3). Splicing text on the picture
Writing text Take adding store text as an example, and gradually complete the writing of text.
$shop_title='测试店铺'; // 添加店铺文字 $drawQr = new ImagickDraw(); // 实例化ImagickDraw $drawQr -> setFillColor(new ImagickPixel('#999999')); // 颜色 $drawQr -> setFontSize('24'); // 大小 $drawQr -> setFont('../../conf/Microsoftyahei.ttf'); // 字体 $drawQr -> setTextAlignment(Imagick::ALIGN_LEFT); // 字体方向 // ps: Imagick::ALIGN_RIGHT 朝右边 Imagick::ALIGN_LEFT 左边 Imagick::ALIGN_CENTER 中间 $drawQr -> setTextEncoding("utf-8"); // 字体编码 $drawQr -> annotation(114,990,$shop_title); // 画出文字 $img -> drawImage($drawQr); // 画在地板上
Detailed interpretation:
1. Instantiate the ImagickDraw class:
$drawQr = new ImagickDraw();
2. Set the font color
$drawQr -> setFillColor(new ImagickPixel('#999999'));
3. Set the font size
$drawQr -> setFontSize('24');
4. Set the font format
$drawQr -> setFont('../../conf/Microsoftyahei.ttf');
5. Set the font direction
$draw->setTextAlignment(Imagick::ALIGN_RIGHT);
ps: Imagick::ALIGN_RIGHT to the right Imagick::ALIGN_LEFT to the left Imagick::ALIGN_CENTER in the middle
6. Set the font encoding
$drawQr -> setTextEncoding("utf-8");
7. Draw the text
$drawQr -> annotation(114,990,$shop_title);
8. Write the font on the base map
$img -> drawImage($drawQr);
Writing text Some pitfalls in this place :
When the font format is not set, Chinese characters will be parsed incorrectly
(no problem with English)
(Chinese character parsing Failure)
(Set the font format to display normally)
The final image our group needs to be passed to the front end in base64 format. Perform the following operations to convert and output the final spliced image to base64.
$dest_img='/data/tmp/' . md5(microtime(true)).'.'.$type; //要生成的图片的路径 $Return = array(); // *图片转换为 base64格式编码* $base64_image = ''; $image_info = getimagesize($dest_img); $image_data = fread(fopen($dest_img, 'r'), filesize($dest_img)); $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data)); $Return['data']=$base64_image; return $Return;
$base64_image
is a picture in base64 format.
It should be noted that the base64 data obtained by the front end contains the '\r\n'
carriage return character, which requires special processing to display the image correctly.
The final merged image will be obtained. You can adjust the size of the spliced image to obtain different images.
Related recommendations:
Upload images and use ImageMagick to generate thumbnails
php to upload images and use ImageMagick generates thumbnails,
The above is the detailed content of How to use ImageMagick to generate base64 images in php (code). For more information, please follow other related articles on the PHP Chinese website!