PHP 自定义明信片

2022-08-30 19:07:12

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

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

我用于创建文本,打开主图像(见下文)以及何时完成imagettftextimagecreatefromjpegimagedestroy

谢谢

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


答案 1

首先,您必须裁剪图像以适合明信片。根据您的图像,您必须执行以下操作:

<?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


答案 2

使用图像复制合并将照片复制到明信片上

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 )

推荐