2013-06-18 44 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