Personal blog duanruilong. Making. IO/blog /
In this paper, the original address duanruilong. Making. IO/blog / 2018/0…
In recent PHP projects, drawing and splicing effects were used. Here are some of the points used in the development process and some of the potholes. Generate base64 image format from ImageMagick for use by the front end.
A few things you need to know
PHP converts images to base64 encoding and base64 images to images and saves the code
The image is base64 encoded
/* Convert the image to base64 encoding */$img = 'uploads/about.png';
$base64_img = base64EncodeImage($img);
echo '<img src="' . $base64_img . '" / >';
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;
}
Copy the code
Base64 images are converted to images and saved
/* Base64 encoding converts to images and saves the corresponding folder */function base64_image_content($base64_image_content.$path){// Match the format of the imageif (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){// Check if the folder exists, if not create, and give the highest permission 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/");
Copy the code
base64
Base64 is a method of representing arbitrary binary data in 64 characters. Base64 is simple. First, prepare an array of 64 characters:
[‘ A ‘, ‘B’, ‘C’… ‘A’, ‘B’, ‘C’… ‘0’, ‘1’,… ‘+’, ‘/’] and then, to deal with binary data, each group 3 bytes, there are 3 by 8 = 24 bit, is divided into four groups, each group is just 6 bit
What if the binary data you want to encode is not a multiple of three and you end up with 1 or 2 bytes left over? Base64 uses \x00 bytes at the end of the complement, and then add 1 or 2 = signs at the end of the code, indicating how many bytes are added, when decoding, will be automatically removed.
JPG images are smaller than PNG images and use PHP’s Imagick class to manipulate images
Imagick specific operation
(1). Create a base image 750px wide by 1046px with a white background and format it as JPG
// Initialize an artboard$img =new Imagick();
$img- > newImage (750104 6,'white'.'jpg');Copy the code
(2). Add requirement pictures on the base map
The premise is that we already know the image link address to merge
$item_img='https://img.alicdn.com/bao/uploaded/i1/1750208593/TB1rgM3hhtnkeRjSZSgXXXAuXXa_!! 0-item_pic.jpg'Step 1: Instantiate the image$imgtwo = new Imagick($item_img); Step 2: Set the size of the image to add$imgtwo- > resizeImage (750764, Imagick: : FILTER_LANCZOS, 1); About resizeImage Parameter Description bool Imagick::resizeImage (int$columns , int $rows , int $filter , float $blur [, bool $bestfit = false]) Parameters: ● Width of columns ● Rows height ● filter for filtering pictures with Gaussian filte depending on the situation ● blur blur=1 for blur blur=1 for sharpening step 3: Merge with the base image$img->compositeImage($imgtwo.$imgtwo- > getImageCompose (), 0, 0); Use the compositeImage (); bool Imagick::compositeImage ( Imagick$composite_object , int $composite , int $x , int $y [, int $channel= Imagick::CHANNEL_ALL]) parameter: ● Composite_object: Imagick object used for merged images ● Composite: merge operation defines operation constants. For details, see the list of merge operation constants ● x: the x-coordinate of the upper left position of the image vertex (0,0) ● y: the y-coordinate of the upper left position of the image vertex (0,0) ● channel: the channel mode is turned on by passing a channel constant. To support multiple channels, multiple channel constants can be combined through the operation of binary operations. 1, add a header information, you can view the image header directly on the web page."Content-Type: img/png");
echo $img; 2, the image can be generated in the specified directory, in the specified directory as img.png$file="./img.png";
$img->writeImage($file); I'm going to do this: header ('Content-type: ' . strtolower ($img->getImageFormat ()) );
$type = strtolower($img->getImageFormat());
$dest_img='/data/tmp/' . md5(microtime(true)).'. '.$type; // The path of the image to be generated, randomly generating the image nameCopy the code
(3) splicing text on pictures
Take adding shop text as an example to gradually complete the writing of text.
$shop_title='Test shop'; // Add store text$drawQr= new ImagickDraw(); // instantiate ImagickDraw$drawQr -> setFillColor(new ImagickPixel('# 999999')); / / color$drawQr -> setFontSize('24'); / / size$drawQr -> setFont('.. /.. /conf/Microsoftyahei.ttf'); / / font$drawQr -> setTextAlignment(Imagick::ALIGN_LEFT); // Font orientation // PS: Imagick::ALIGN_RIGHT to the right Imagick::ALIGN_LEFT Imagick::ALIGN_CENTER center$drawQr -> setTextEncoding("utf-8"); // Font encoding$drawQr- > the annotation (114990,$shop_title); // Draw the text$img -> drawImage($drawQr); // Draw on the floorCopy the code
Detailed interpretation:
- 1, Instantiate ImagickDraw;
$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 orientation
$draw->setTextAlignment(Imagick::ALIGN_RIGHT);
Ps: Imagick::ALIGN_RIGHT to the right Imagick::ALIGN_LEFT Imagick::ALIGN_CENTER center
- 6. Set the font encoding
$drawQr -> setTextEncoding("utf-8");
- 7. Draw the text
(114990, $$drawQr - > an annotation shop_title);
- 8. Write a font on the base image
$img -> drawImage($drawQr);
Write text to this place for some pits:
[Bug Mc-108966] – Chinese text will be parsed incorrectly if font format is not set (English is fine)
(Chinese character parsing failure)
(Set the font format to be displayed normally)
(4). Image base64 export
Our group will finally get the picture in base64 format to pass to the front end, the following operations, we finally spliced to the picture Base64 conversion output.
$dest_img='/data/tmp/' . md5(microtime(true)).'. '.$type; // The path to the image to be generated$Return= array(); // * Convert the image to base64 encoding *$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;
Copy the code
$base64_image is the image in base64 format.
It should be noted that the base64 data obtained from the front end contains the ‘\r\n’ carriage return character, which requires special processing to display the image correctly.
(Final merged image)
(Adjust the size of the Mosaic image to get different pictures)
Let’s have one last singles jayne!!
If you like it, welcome to start