<?php
namespace app\common\service\qrcode\bargain;
use Grafika\Color;
use Grafika\Grafika;
use app\common\service\qrcode\Base;
class Goods extends Base
{
private $active;
private $goods;
private $user_id;
public function __construct($active, $goods, $user)
{
parent::__construct();
$this->active = $active;
$this->goods = $goods;
$this->user_id = $user ? $user['user_id'] : 0;
}
public function getImage()
{
if (file_exists($this->getPosterPath())) {
return $this->getPosterUrl();
}
$wxappId = $this->active['wxapp_id'];
$backdrop = __DIR__ . '/../resource/goods_bg.png';
$goodsUrl = $this->saveTempImage($wxappId, $this->goods['goods_image'], 'goods');
$scene = "aid:{$this->active['active_id']},uid:" . ($this->user_id ?: '');
$qrcode = $this->saveQrcode($wxappId, $scene, 'pages/bargain/goods/index');
return $this->savePoster($backdrop, $goodsUrl, $qrcode);
}
private function savePoster($backdrop, $goodsUrl, $qrcode)
{
$editor = Grafika::createEditor(['Gd']);
$fontPath = Grafika::fontsDir() . '/' . 'st-heiti-light.ttc';
$editor->open($backdropImage, $backdrop);
$editor->open($goodsImage, $goodsUrl);
$editor->resizeExact($goodsImage, 690, 690);
$editor->blend($backdropImage, $goodsImage, 'normal', 1.0, 'top-left', 30, 30);
$fontSize = 30;
$goodsName = $this->wrapText($fontSize, 0, $fontPath, $this->goods['goods_name'], 680, 2);
$editor->text($backdropImage, $goodsName, $fontSize, 30, 750, new Color('#333333'), $fontPath);
$editor->text($backdropImage, $this->active['floor_price'], 38, 62, 964, new Color('#ff4444'));
$editor->open($qrcodeImage, $qrcode);
$editor->resizeExact($qrcodeImage, 140, 140);
$editor->blend($backdropImage, $qrcodeImage, 'normal', 1.0, 'top-left', 570, 914);
$editor->save($backdropImage, $this->getPosterPath());
return $this->getPosterUrl();
}
private function wrapText($fontsize, $angle, $fontface, $string, $width, $max_line = null)
{
$content = "";
$letter = [];
for ($i = 0; $i < mb_strlen($string, 'UTF-8'); $i++) {
$letter[] = mb_substr($string, $i, 1, 'UTF-8');
}
$line_count = 0;
foreach ($letter as $l) {
$testbox = imagettfbbox($fontsize, $angle, $fontface, $content . ' ' . $l);
if (($testbox[2] > $width) && ($content !== "")) {
$line_count++;
if ($max_line && $line_count >= $max_line) {
$content = mb_substr($content, 0, -1, 'UTF-8') . "...";
break;
}
$content .= "\n";
}
$content .= $l;
}
return $content;
}
private function getPosterPath()
{
$tempPath = WEB_PATH . 'temp' . '/' . $this->active['wxapp_id'] . '/';
!is_dir($tempPath) && mkdir($tempPath, 0755, true);
return $tempPath . $this->getPosterName();
}
private function getPosterName()
{
return 'bargain_active_' . md5("{$this->user_id}_{$this->active['active_id']}") . '.png';
}
private function getPosterUrl()
{
return \base_url() . 'temp/' . $this->active['wxapp_id'] . '/' . $this->getPosterName() . '?t=' . time();
}
}