2013-06-18 47 views
1

嗨,我使用下面的腳本,它完美的作品。PHP - 將水印圖像保存到目錄

我的問題是,我如何替換原來的圖像與水印的留下相同的文件名和擴展名?

$stamp = imagecreatefrompng(base_static_url().$this->marker_url); 
$im = imagecreatefromjpeg($img_path); 
// Set the margins for the stamp and get the height/width of the stamp image 
$marge_right = 10; 
$marge_bottom = 10; 
$sx = imagesx($stamp); 
$sy = imagesy($stamp); 

// Copy the stamp image onto our photo using the margin offsets and the photo 
// width to calculate positioning of the stamp. 
imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp)); 

// Output and free memory 
header('Content-type: image/png'); 
imagepng($im); 
imagedestroy($im); 

我tryed:

file_put_contents($img_path, imagecreatefromjpeg($im)); 

不過的了:

Error: failed to open stream: HTTP wrapper does not support writeable connections 

而且我也試過:

file_put_contents($img_path, $im); 

然後我得到了一個新的錯誤:

Error: file_put_contents(): supplied resource is not a valid stream resource 

回答

2

你可以嘗試:

imagejpeg($im, $img_path); 

imagejpeg()需要被描述爲一個說法:

The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.

然而,作爲另一個用戶提及 - 如果你想要將文件保存到遠程服務器,則必須以不同的方式執行此操作。一種方法可能是使用PHP的FTP功能:http://www.php.net/manual/en/ftp.examples-basic.php

+0

確定itryed imagejpeg(),因爲原來的它是一個JPG要被替換。問題是http不允許取消鏈接,並且似乎傳遞給imagejpeg()的路徑不正常,但可以加水印:/我收到:** imagejpeg()[function.imagejpeg]:無法打開'http:// localhost/site/uploads/img/iphone.jpg'寫作:沒有這樣的文件或目錄** – sbaaaang

+0

你確定這是正確的網址嗎?錯誤消息是說該路徑不存在。你的php錯誤日誌中是否有其他錯誤或警告? – Joe

+0

嗯路徑是絕對正確的:(我授予777訪問只是爲了測試:( – sbaaaang

2

那麼錯誤解釋這一切:

Error: failed to open stream: HTTP wrapper does not support writeable connections 

的HTTP包裝(PHP的一部分,讓您使用http://協議中的URI)無法寫入網頁地址。這是有道理的,因爲想象一下,如果有人可以運行這個:

file_put_contents('http://google.com', '<!--malicious script-->'); 

併購接管谷歌!

要將文件保存到遠程網絡服務器,您需要使用FTP,SFTP或類似文件訪問其文件系統。 PHP已經建立了interfacing with FTP

但是,我懷疑您嘗試修改的文件位於執行此PHP腳本的服務器上。在這種情況下,您需要使用服務器上的文件路徑(可能類似/var/www/images/image.jpg),而不是file_put_contents()中的網址(http://www.yoursite.com/images/image.jpg)。

+0

我試過了:** file_put_contents('./ uploads/img/iphone.jpg',imagejpeg($ im)); **它用相同的名稱和分機取代原來的圖像,但圖像現在是空的:P – sbaaaang

+0

@badbetonbreakbutbedbackbone這是因爲imagejpeg($ im)回聲圖像而不是返回它(帶有一個參數,它會重新生成一個布爾值來指示成功或失敗)。要寫入文件,請將文件名作爲第二個參數傳遞:'imagejpeg($ im,'./uploads/img/iphone.jpg')' –

+0

+1確定您保存了我的生活,對不起​​,但我必須接受其他老兄的回答,因爲他告訴首先使用imagepng():P – sbaaaang