When working with images in PHP, it is often necessary to crop them.
How to put the cropped picture into the MySQL database is an interesting question.
First, get the post-upload file:
$picFile = $_files["Picfilename"]; $picType = $picFile ["type"]; $picData = file_get_contents ($tempFile);
If you do not need to change the image size and directly into MySQL, you can easily implement the following
$tempFile = $picFile ["Tmp_name"]; $picData = Base64_encode ($picData); $query = "INSERT into image (imgid, image, Imgtype) values ( null, ' $picData ', ' $picType ' );"; $link->query ($query);
But if you want to change the size of the picture and get the picture data as a stream of characters, you need a little bit of finesse:
Finish cropping the picture first, get the picture object
List ($picW, $picH) = getimagesize ($tempFile); if ($picW >600) {//exceeds size $src = Imagecreatefromjpeg ($tempFile);//Get Original data $nW =550; $nH = $picH * $nW/$picW; $newPicTemp = Imagecreatetruecolor ($nW, $nH); Create a color Picture object imagecopyresampled ($newPicTemp, $SRC, 0,0,0,0, $nW, $nH, $picW, $picH); }
This step after Newpictemp is the resource type of picture data, the problem came, observe the above code, FILE_GET_CONTENTS returns the type is a string, is also the Base64_encode parameter type. How to convert resource to string type. After learning that PHP has a function
String ob_get_contents (void)
Returns the contents of the output buffer as a string.
So the idea is to output the resource image to a buffer, and then use an object to get its contents. The code is as follows
Ob_start (); Open Output Buffer imagejpeg ($newPicTemp);//This function can display the image, but also the data output $imgContent = Ob_get_contents ();//Get character stream Ob_ End_clean (); Close and clear the buffer $picData = Base64_encode ($imgContent);//Don't forget to transcode
In this way, you get the change size of the picture character stream, can be stored in MySQL
Final destruction of temporary data
Imagedestroy ($SRC); Imagedestroy ($newPicTemp);
If you need to read and display the picture, You can use the following code
$query =" Select Image, Imgtype from image where Imgid = $imgid; "; $result = $link->query ($query); $row = Mysqli_fetch_array ($result); $data = Base64_decode ($row ["image"]); $type = $row ["Imgtype"]; Ob_clean (); Header ("Content-type: ' $type '"); Echo $data;
reference php.net
The above describes the PHP cropped image and stored in MySQL, including aspects of the content, I hope to be interested in PHP tutorial friends helpful.