2010-10-16 26 views
0

我正在通过允许用户上传图像并应用样式边框或框架(例如云,星星,天空等)来改进我的一个Facebook应用。用户还可以保存图像,并在图像应用后使用边框。这说明好一点什么,我需要:在PHP中为图像添加样式化背景

http://zbrowntechnology.info/ImgDisp/imgdisp.php 

如果您有任何疑问或需要更多资料,请让我知道..我会编辑这个职位。通过使用CSS3

回答

3

使用imagecopy()。该页面上的示例是使用imagecopymerge()的透明度选项完成的,但我不认为你需要这样做。

使用imagecopy的(),你会指定X/Y坐标用于定位:

imagecopy($borderimage, $topimage, 20, 20, 0, 0, $width, $height);

$width$height将顶部图像的整个宽度和高度。您需要将2020替换为测量边框图像在边框周围显示的多少。您可能需要将顶部图像调整为所需的精确尺寸,否则它可能会与边界稍微偏离右侧或底部。 (见imagecopyresampled()

编辑:

这里有一个粗略的方式来完成整个过程(假设chosenborder.png是他们选择的边框,uploadedimage.png是他们上传的图片如果它是一个不同的图像类型,你会使用。 corresponding function)。

$borderx = 20; // The width of our border 
$border = imagecreatefrompng("chosenborder.png"); 
$topimage = imagecreatefrompng("uploadedimage.png"); 
$bordersize = getimagesize($border); 
$topimagesize = getimagesize($topimage); 

/* The new dimensions of topimage. $borderx*2 means we account for 
    the border on both left and right, top and bottom. */ 
$newx = $bordersize[0] - ($borderx*2); 
$newy = $bordersize[1] - ($borderx*2); 
imagecopyresampled($topimage_scaled, $topimage, 0, 0, 0, 0, 
       $newx, $newy, $topimagesize[0], $topimagesize[1]); 

/* Merge the images */ 
imagecopy($border, $topimage_scaled, $borderx, $borderx, 
       0, 0, $width, $height); 
/* Output the image */ 
imagepng($border, "newimage.png"); 
/* Free up the memory occupied by the image resources */ 
imagedestroy($border); 
imagedestroy($topimage); 

用户上传自己的形象之后,发现chosenborder.pnguploadedimage.png,运行上面的脚本,然后显示newimage.png给用户,你是好去。只要确保你在临时图像资源上拨打imagedestroy(),否则他们会吃掉内存。

如果您不想将生成的图像保留在服务器上,您可以省略第二个参数imagepng(),这将使图像信息直接作为图像发送到浏览器,在这种情况下,您需要编写correct image HTTP headers

0

客户端解决方案:

结账的CSS3属性border-image (这么想的满足节能与边框的IMG的要求)通过合并

服务器端解决方案2个不同的图像:

<?php 


$imgFile = 'img.jpg'; 
$brdFile = 'brd.jpg'; 
$img = addBorder($imgFile,$brdFile); 
outputImage($img); 

function addBorder($imgFile,$brdFile) 
{ 
    $img=imagecreatefromjpeg($imgFile); 
    $brd=imagecreatefromjpeg($brdFile); 

    $imgSize = getimagesize($imgFile); 
    $brdSize = getimagesize($brdFile); 


    //NOTE: the border img MUST be bigger then the src img 
    $dst_x = ceil(($brdSize[0] - $imgSize[0])/2); 
    $dst_y = ceil(($brdSize[1] - $imgSize[1])/2); 


    imagecopymerge ($brd, $img, $dst_x, $dst_y, 0, 0, $imgSize[0], $imgSize[1] ,100 ); 

    return $brd; 
} 

function outputImage($img) 
{ 
    header('Content-type: image/png'); 
    imagepng($img); 
} 

?> 
+0

我认为OP正在寻找一个PHP脚本,将边界与原始图像合并为一个图像,以便用户可以将整个图像保存为一个文件。 – 2010-10-16 02:01:44

+0

也许是或者可能不是......在这两种解决方案中都有优点和缺点。通过使用css,你可以在1行中解决问题,并且你不需要在服务器端改变任何东西,但是一些旧的浏览器可能不支持css3。 通过使用GD可以肯定它是跨浏览器的,但是您需要详细说明每个图像,并且在服务器端增加详细说明 – Cesar 2010-10-16 02:04:17