方法一:前端JS生成(推薦)
注意:
1.這個網頁只能截圖圖片效果代碼,其它任何html效果都不能有,不然截圖就不準確
2.如果要生成的圖片DIV內容中引用了第三個方的圖片,就是不使用同一個域名下的圖片,需要把后端把圖片轉為Base64才可以生成截圖、不然會造成跨域的問題,生成的圖片會是空白的
圖片轉為Base64后的顯示方式:
<img src="data:image/jpeg;base64,{$PosterParameters['imgp_Base64']}" />
例子:
<div class="container" id="capture-target"><div class="img">{notempty name="$PosterParameters['img_Base64']"}<img src="data:image/jpeg;base64,{$PosterParameters['img_Base64']}" />{/notempty}</div><div class="username"><p>{notempty name="$PosterParameters['name']"}{$PosterParameters['name']}{/notempty}</p></div><div class="invite_text"><p>{notempty name="$PosterParameters['invite_text']"}{$PosterParameters['invite_text']}{/notempty}</p></div><div class="live_time_day"><p>{notempty name="$PosterParameters['day']"}{$PosterParameters['day']}{/notempty}</p></div><div class="live_time"><p>{notempty name="$PosterParameters['hi']"}{$PosterParameters['hi']}{/notempty}</p></div><div class="imgp">{notempty name="$PosterParameters['imgp_Base64']"}<img src="data:image/jpeg;base64,{$PosterParameters['imgp_Base64']}" />{else /}{notempty name="$PosterParameters['imgp']"}<img src="{$PosterParameters['imgp']}" />{/notempty}{/notempty}</div><div class="title"><p id="myDiv">{notempty name="$PosterParameters['title']"}{$PosterParameters['title']}{/notempty}</p></div><div class="qr-code"><img src="{notempty name="$PosterParameters['QRcodeUrl']"}{$PosterParameters['QRcodeUrl']}{/notempty}" width="160px" height="160px" /></div></div>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>網頁內容轉圖片示例</title><!-- 引入html2canvas庫 --><script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
</head>
<body><!-- 截圖內容 -->
<div id="capture-target"><h1>歡迎來到我的網站</h1><p>這是一個用于演示如何將網頁內容轉換成圖片的例子。</p>
</div><!-- 按鈕觸發截圖 -->
<button onclick="captureAndSave()">點擊截圖保存</button><script>// 圖片下載函數,增強對不同瀏覽器的支持function downloadImage(dataURL, filename) {const link = document.createElement('a');link.href = dataURL;link.download = filename;document.body.appendChild(link); // 確保元素添加到DOM中以觸發點擊事件link.click();document.body.removeChild(link); // 下載后移除元素}// 增強的截圖并保存的函數,優化參數處理與錯誤提示async function captureAndSave() {try {const targetElement = document.querySelector('#capture-target');const dpiScale = window.devicePixelRatio || 1;const qualityFactor = 0.9; // 默認質量因子,可以根據需要調整const format = 'image/png'; // 圖片輸出格式,可根據需要更改為 'image/png' 等const scale = dpiScale >= 2 ? dpiScale : 2; // 動態調整縮放比例,優先考慮DPR,至少為2以保證清晰度const canvas = await html2canvas(targetElement, {scale,dpi: 300,logging: false,useCORS: true,allowTaint: true,});// 根據圖片格式動態調整dataURL的mime類型const mimeType = format === 'image/jpeg' ? 'image/jpeg' : 'image/png';const imageDataURL = canvas.toDataURL(mimeType, qualityFactor);// 動態檢測瀏覽器對MIME類型的兼容性,必要時轉換為Blob下載if (navigator.msSaveBlob) { // IE/Edge 特殊處理const blob = await (await fetch(imageDataURL)).blob();navigator.msSaveBlob(blob, 'screenshot.' + (format === 'image/jpeg' ? 'jpg' : 'png'));} else {downloadImage(imageDataURL.replace(mimeType, 'image/octet-stream'), 'screenshot.' + (format === 'image/jpeg' ? 'jpg' : 'png'));}} catch (error) {//alert('截圖保存時發生錯誤,請檢查瀏覽器控制臺詳情。'); // 提供用戶友好提示console.error('截圖時發生錯誤:', error);}}
</script>
方法二:后端生成(沒有測試)
/*** @name 生成海報* @author 峰神* @date 2024-06-28* @param array $postData 必填 提交數組* @param int [必填/選填] type 生成類型 默認0=偽直播邀請海報* @ruturn array*/public function CreatePoster(array $postData=[],int $type=0){$tmp_bg_image = 'static/images/live_share.png';//背景圖路徑//獲取二維碼,調用了上邊那個方法$qrcode_img = 'static/images/portrait.png';// $qr_res = $this->extendQrcode();// if($qr_res['status']){// $qrcode_img = $qr_res['data'];// }//新文件名$share_path = 'upload/share/';is_dir($share_path) OR mkdir($share_path, 0777, true);$share_img = $share_path.'1.jpg';$this->composite_picture($tmp_bg_image, $qrcode_img, $share_img, false, '', '', false, '', 150, 510); //模板背景, 二維碼, 海報, 二維碼是否縮小, 二維碼縮小的寬度,二維碼縮小的高度,是否等比例縮放, 文字, 二維碼在x軸的位置, 二維碼在y軸的位置$result = ['status'=>true, 'data'=>$share_img];return json_encode($result, 320);}/** 合并圖片* @ $bg_img 背景圖片* @ $qrcode_img 二維碼圖片* @ $new_filename 新文件名* @ $is_suoxiao 組合的圖片是否縮小* @ $n_w 縮小的寬* @ $n_h 縮小的高* @ $is_per 是否按比例縮小* @ $text 文字* @ $s_width 要組合的圖片在x軸的位置* @ $s_height 要組合的圖片在y軸的位置*/public function composite_picture($bg_img, $qrcode_img, $new_filename, $is_suoxiao, $n_w='', $n_h='', $is_per=false, $text='', $s_width='0', $s_height='0'){if($is_suoxiao){$src_im = $this->imgsuoxiao($qrcode_img, $n_w, $n_h, $is_per);}else{$src_im = $qrcode_img;}$bgimg = imagecreatefromstring(file_get_contents($bg_img));//背景圖$src = imagecreatefromstring(file_get_contents($src_im));//組合圖list($src_w, $src_h) = getimagesize($src_im);imagecopy($bgimg, $src, $s_width, $s_height, 0, 0, $src_w, $src_h);list($bgimg_w, $bgimg_h, $bgimg_type) = getimagesize($bg_img);switch ($bgimg_type) {case 1://GIFheader('Content-Type: image/gif');header('Content-Disposition: inline; filename="image.gif"');$result = imagegif($bgimg, $new_filename);break;case 2://JPGheader('Content-Type: image/jpeg');header('Content-Disposition: inline; filename="image.jpg"');imagejpeg($bgimg, $new_filename);break;case 3://PNGheader('Content-Type: image/png');header('Content-Disposition: inline; filename="image.png"');imagepng($bgimg, $new_filename);break;default:break;}imagedestroy($bgimg);imagedestroy($src);if($text){$newss = $this->numimage($text,$new_filename,15,3,230,720);return $newss;}else{return $new_filename;}return $new_filename;// exit;}//縮小圖片public function imgsuoxiao($filename, $n_w, $n_h, $is_per=false){list($width, $height, $dst_type)=getimagesize($filename);if($is_per){$per=0.3;$n_w=$width*$per;$n_h=$height*$per;}switch ($dst_type) {case 2://JPG$img=imagecreatefromjpeg($filename);break;case 3://PNG$img = imagecreatefrompng($filename);break;default:break;}$new=imagecreatetruecolor($n_w, $n_h);//copy部分圖像并調整imagecopyresized($new, $img,0, 0,0, 0,$n_w, $n_h, $width, $height);//圖像輸出新圖片、另存為imagejpeg($new, $filename);imagedestroy($new);imagedestroy($img);return $filename;}/*** 像圖片中添加文字* @param $txt 文本文字* @param $image 圖片路徑* @param $size 文字大小* @param $scale 文字旋轉度* @param $x 在x軸上的位置* @param $y 在y軸上的位置* @param $color 字體顏色*/public function numimage($txt,$image,$size,$scale,$x,$y, $color="黑色"){list($dst_w, $dst_h, $dst_type) = getimagesize($image);switch ($dst_type) {case 2://JPG$im = imagecreatefromjpeg($image);break;case 3://PNG$im = imagecreatefrompng($image);break;default:break;}$textcolor = imagecolorallocate($im, 0, 0, 0);if($color=="白色"){$textcolor = imagecolorallocate($im, 255, 255, 255);}$qr_size = imagesx($im);$font = realpath('static/STSONG.TTF'); //引入字體imagettftext($im, $size,0,$x,$y, $textcolor, $font, $txt);$myImage = ImageCreate(245,245); //參數為寬度和高度imagecopyresampled($myImage, $im, 0, 0, 0, 0, 0, 80, 10, 10); //重新組合圖片并調整大小header("Content-type: image/jpeg");imagejpeg($im, $image);imagedestroy($im);return $image;}
Thinkphp5 生成二維碼并與背景圖、文字組合生成分享海報_tp5+phpqrcode二維碼下方帶文字-CSDN博客