PHP定制明信片

时间:2011-11-19 19:55:24

标签: php image gd

我正在我的网站上创建一个新功能,允许人们向朋友发送明信片。在这一部分,他们可以选择他们想要发送的图像(他们已经将图像上传到他们的个人资料 - >我的图片部分)

我正在使用php函数创建右侧文本,但如何使用文本将另一个图像添加到此图像?

我使用imagettftext创建文字,imagecreatefromjpeg打开主图片(见下文)和imagedestroy完成后

感谢

我正在使用这张明信片: postcard-template.jpg

2 个答案:

答案 0 :(得分:41)

首先,您必须裁剪图像以适合您的明信片。 根据您的图像,您需要做的是:

<?php

$sourceImage = './postcard-template.jpg';
$uploadedImage = '/path/to/image/hong-kong2.jpg'; // let's get hong kong as example
$mime = '';
$font = '/path/to/font/arial.ttf'; 

function CroppedThumbnail($source, $width, $height, &$mime) {
  $data = getimagesize($source);
  $sourceWidth = $data[0];
  $sourceHeight = $data[1];
  $mime = $data['mime'];
  $image = imagecreatefromjpeg($source);
  $sourceRatio = $sourceWidth/$sourceHeight;
  if (($width/$height) > $sourceRatio) {
    $newHeight = $width/$sourceRatio;
    $newWidth = $width;
  }
  else {
    $newWidth = $height*$sourceRatio;
    $newHeight = $height;
  }
  $croppedImage = imagecreatetruecolor(round($newWidth), round($newHeight));
  imagecopyresampled($croppedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $sourceWidth, $sourceHeight);
  $thumb = imagecreatetruecolor($width, $height);
  imagecopyresampled($thumb, $croppedImage, 0, 0, (($newWidth/2)-($width/2)), (($newHeight/2)-($height/2)), $width, $height, $width, $height);
  imagedestroy($croppedImage);
  imagedestroy($image);
  return $thumb;
}

// Create the cropped image first
$newThumb = CroppedThumbnail($uploadedImage,240,315, $mime);
switch($mime) {
  case 'image/gif':
    $image = imagecreatefromgif($sourceImage);  
    break;
  case 'image/jpeg':
    $image = imagecreatefromjpeg($sourceImage);  
    break;
  case 'image/png':
    $image = imagecreatefrompng($sourceImage);  
    break;
  default:
    // error or stop script
    break;
}
$message = "this is some text\nsome other text\ntext text";

imagettftext($image, 21, 0, 320, 255, imagecolorallocate($image, 0, 0, 0), $font, $message);
imagecopy($image, $newThumb, 40, 40, 0, 0, 240, 315); 
header('Content-Type: image/jpeg');
imagejpeg($image); 
imagedestroy($image);

例如我使用此图像(需要裁剪):

testimage

然后输出:

final

答案 1 :(得分:0)

使用imagecopymerge将照片复制到明信片上

bool imagecopymerge ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h , int $pct )