Home >Backend Development >PHP Tutorial >Share the method of receiving binary files and converting them into images in PHP
This article introduces an example of PHP receiving binary code and converting it into a picture. Friends in need can refer to it.
php develops a Flash online program for cropping pictures and generating pictures. The binary data of the picture is POSTed to php through Flash, and php generates the picture and saves it. It is not possible to use $_POST to receive data. PHP only recognizes application/x-www.form-urlencoded standard data types by default. Therefore, content such as text/xml or soap or application/octet-stream cannot be parsed. If you use the $_POST array to receive it, it will fail! Therefore, the prototype is retained and handed over to $GLOBALS['HTTP_RAW_POST_DATA'] to receive it. In addition, php://input can also implement this function. php://input allows reading the raw data of POST. It puts less pressure on memory than $HTTP_RAW_POST_DATA and does not require any special php.ini settings. php://input and $HTTP_RAW_POST_DATA cannot be used with enctype=”multipart/form-data”. Use JPGEncoder in Flash to convert BitMapData into binary, and then post it to php code. 1, php page code <?php /** * 生成图片,接收二进制数据 * edit by bbs.it-home.org */ $filename="teststream.jpg";//要生成的图片名字 $xmlstr = $GLOBALS[HTTP_RAW_POST_DATA]; if(empty($xmlstr)) $xmlstr = file_get_contents('php://input'); $jpg = $xmlstr;//得到post过来的二进制原始数据 $file = fopen("cache/pic/".$filename,"w");//打开文件准备写入 fwrite($file,$jpg);//写入 fclose($file);//关闭 ?> 2, application in thinkphp; <?php //保存头像 public function saveAvatar(){ $filename = intval($_GET['id']).'.jpg'; $xmlstr = $GLOBALS['HTTP_RAW_POST_DATA']; if(empty($xmlstr)) { $xmlstr = file_get_contents('php://input'); } if(!$xmlstr){ exit( '没有接收到数据流.' ); } //by bbs.it-home.org $jpg = $xmlstr;//得到post过来的二进制原始数据 $file = fopen("./Public/Uploads/AVATAR/".$filename,"w");//打开文件准备写入 fwrite($file,$jpg);//写入 fclose($file);//关闭 } ?> |