php在数据流(内存)中操纵远程数据
html5上傳圖片時(shí)可用php://input的數(shù)據(jù)流來運(yùn)作.
例如:
1 if($in = fopen('php://input', "rb")) 2 while($buff = fread($in, 4096)) 3 fwrite('e:\\1.jpg', $buff);?如果遇到要加水印,那只有imagecreatefromjpg($filename),再打一次剛關(guān)閉的文件.
作為一個(gè)效率癖,這是不被允許的,有直接操縱數(shù)據(jù)流的方法嗎?答案是有, php官方手冊(cè)上有 "支持的協(xié)議和封裝協(xié)議",其中的data://大家應(yīng)該都很熟悉.
我們可以利用它完成在數(shù)據(jù)流中直接操縱圖片(水印,縮略圖之類),以下代碼為了方便我就直接file_get_contents().
1 $file_path = 'http://www.baidu.com/img/shouye_b5486898c692066bd2cbaeda86d74448.gif'; 2 $stream = file_get_contents($file_path); 3 print_r(getimagesize("data://text/plain;base64," . base64_encode($stream))); 4 $new_img = imagecreatefromgif("data://text/plain;base64," . base64_encode($stream)); 5 print_r($new_img); 6 imagejpeg($new_img, 'E:\WEB\uploads\test.jpg', 100);成功轉(zhuǎn)換格式了.
這個(gè)方法固然好,但一次base64看起來不是那么爽,還有更簡單的嗎?當(dāng)然,?stream_register_wrapper — 注冊(cè)一個(gè)用 PHP 類實(shí)現(xiàn)的 URL 封裝協(xié)議
我們看看代碼:
1 class getImgStream{ 2 3 private $imgStream; 4 private $position; 5 6 function stream_open($path, $mode, $options, &$opened_path){ 7 $url = parse_url($path); 8 $this->imgStream = $GLOBALS[$url["host"]]; 9 $this->position = 0; 10 return true; 11 } 12 13 function stream_read($count){ 14 $ret = substr($this->imgStream, $this->position, $count); 15 $this->position += strlen($ret); 16 return $ret; 17 } 18 19 function stream_stat(){ 20 //maxmemory: 5 * 1024 * 1024; 21 $fp = fopen("php://temp/maxmemory:5242880", 'r+'); 22 fwrite($fp, $this->imgStream); 23 $fstat = fstat($fp); 24 fclose($fp); 25 return $fstat; 26 } 27 28 function stream_eof(){ 29 return $this->position >= strlen($this->imgStream); 30 } 31 32 function stream_tell(){ 33 return $this->position; 34 } 35 36 function stream_close(){ 37 unset($this->imgStream, $this->position); 38 } 39 40 } 41 42 $file_path = 'http://www.baidu.com/img/shouye_b5486898c692066bd2cbaeda86d74448.gif'; 43 $stream = file_get_contents($file_path); 44 45 stream_wrapper_register("image", "getImgStream"); 46 47 print_r(getimagesize('image://stream')); 48 $new_img = imagecreatefromgif('image://stream'); 49 print_r($new_img); 50 imagejpeg($new_img, 'E:\WEB\uploads\test.jpg', 100);?沒有意外因?yàn)檫@個(gè)函數(shù)支持PHP 4 >= 4.3.0, PHP 5,這樣才像效率癖干的事,但代碼看起來多了好多,而且小小的圖片.也看不出多大效率.
經(jīng)測(cè)試,同一張本地圖片,方法一平均43ms,方法二平均39ms
?
by:http://www.cnblogs.com/wc1217/archive/2013/04/02/2995961.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的php在数据流(内存)中操纵远程数据的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于UDP的组播网络程序
- 下一篇: 学习PHP时的一些总结(五)