PHP定制明信片

Eri*_*ker 22 php gd image

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

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

imagettftext用来创建文本,imagecreatefromjpeg打开主图像(见下文)和imagedestroy完成后

谢谢

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

Boo*_*eus 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);
Run Code Online (Sandbox Code Playgroud)

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

testimage

然后它会输出:

最后

  • +1哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇! (6认同)