一号优惠经验分享网
51福利网的各种薅羊毛福利经验笔记

图片自动拼接的php代码

网站示例:

①☞两两图片纵向拼接-自动分组

51福利网

②☞两两图片横向拼接-自动分组

以下是自己慢慢研究每个代码都是可以用的,按需选择,

实例1:简单的2张图片纵向批量拼接的代码

<?php

// 源文件夹路径
$sourceFolder = 'comeimg';

// 目标文件夹路径
$targetFolder = 'toimg';

// 读取源文件夹中所有图片文件
$files = glob($sourceFolder . '/*.{jpg,jpeg,png,gif}', GLOB_BRACE);

// 遍历所有文件,每次读取两张图片,拼接成一张图片并保存到目标文件夹中
for ($i = 0; $i < count($files); $i += 2) {

    // 读取两张图片
    $img1 = imagecreatefromjpeg($files[$i]);
    list($width1, $height1) = getimagesize($files[$i]);

    $img2 = imagecreatefromjpeg($files[$i + 1]);
    list($width2, $height2) = getimagesize($files[$i + 1]);

    // 创建一个新的画布,大小为两张图片的宽度和高度之和
    $canvas = imagecreatetruecolor($width1, $height1 + $height2);

    // 拷贝第一张图片到新画布中
    imagecopy($canvas, $img1, 0, 0, 0, 0, $width1, $height1);

    // 拷贝第二张图片到新画布中
    imagecopy($canvas, $img2, 0, $height1, 0, 0, $width2, $height2);

    // 生成新的文件名:原文件名+“_merged.jpg”
    $newFilename = pathinfo($files[$i], PATHINFO_FILENAME) . '_merged.jpg';

    // 写入目标文件夹中
    imagejpeg($canvas, $targetFolder . '/' . $newFilename);

    // 释放内存
    imagedestroy($canvas);
    imagedestroy($img1);
    imagedestroy($img2);
}
?>

实例2 带前台上传,操作,导出的横向图片拼接代码,可以直接放自己网站用

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // 接收上传的图片文件
  $file1 = $_FILES['file1'];
  $file2 = $_FILES['file2'];

  // 检查是否上传成功
  if ($file1['error'] !== UPLOAD_ERR_OK || $file2['error'] !== UPLOAD_ERR_OK) {
    die('上传失败:' . var_export($file1['error'], true) . var_export($file2['error'], true));
  }

  // 创建图片资源
  $img1 = imagecreatefromjpeg($file1['tmp_name']);
  $img2 = imagecreatefromjpeg($file2['tmp_name']);

  // 拼接图片
  $width1 = imagesx($img1);
  $height1 = imagesy($img1);
  $width2 = imagesx($img2);
  $height2 = imagesy($img2);

  $canvasWidth = $width1 + $width2;
  $canvasHeight = max($height1, $height2);

  $canvas = imagecreatetruecolor($canvasWidth, $canvasHeight);

  imagecopy($canvas, $img1, 0, 0, 0, 0, $width1, $height1);
  imagecopy($canvas, $img2, $width1, 0, 0, 0, $width2, $height2);

  // 保存结果图片到本地
  $resultFilename = uniqid() . '.jpg';
  imagejpeg($canvas, $resultFilename);

  // 释放资源
  imagedestroy($canvas);
  imagedestroy($img1);
  imagedestroy($img2);

  // 返回结果图片文件名
  die($resultFilename);
}
?>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>图片拼接工具</title>
</head>

<body>
  <input type="file" name="file1" accept="image/*">
  <input type="file" name="file2" accept="image/*">
  <button id="operate-btn">拼接</button>
  <p id="result"></p>

  <script>
    const operateBtn = document.getElementById('operate-btn');
    const resultElem = document.getElementById('result');
    operateBtn.addEventListener('click', () => {
      const file1 = document.querySelector('input[name="file1"]').files[0];
      const file2 = document.querySelector('input[name="file2"]').files[0];
      if (file1 && file2) {
        const formData = new FormData();
        formData.append('file1', file1);
        formData.append('file2', file2);
        fetch(location.href, {
            method: 'POST',
            body: formData
          })
          .then(response => response.text())
          .then(resultFilename => {
            resultElem.innerHTML = `
              <img src="${resultFilename}" alt="结果">
              <a href="${resultFilename}" download="result.jpg">下载结果图片</a>
            `;
          });
      } else {
        resultElem.innerHTML = '<p>请先选择两张图片</p>';
      }
    });
  </script>
</body>

</html>

这个示例将 PHP 代码和 HTML/JavaScript 代码组合在一起,实现了上传两个图片文件,通过 PHP 对两张图片进行横向拼接,并返回拼接后的结果图片文件名,使用 JavaScript 显示结果图片和下载结果图片的功能。

需要注意的是,这只是一个简单的示例代码,如果需要正式使用,还需要进行优化,例如添加文件格式校验、数据上传进度显示等功能。同时需要注意的是,该示例代码仅支持 PHP 7.0 及以上版本。

实例3.增加批量上传

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $files = $_FILES['files'];

  // 检查是否上传成功
  foreach ($files['error'] as $error) {
    if ($error !== UPLOAD_ERR_OK) {
      die('上传失败');
    }
  }

  // 创建图片资源
  $canvasWidth = 0;
  $canvasHeight = 0;
  $imgList = array();
  foreach ($files['tmp_name'] as $i => $tmpName) {
    $img = imagecreatefromjpeg($tmpName);

    $width = imagesx($img);
    $height = imagesy($img);

    $canvasWidth += $width;
    $canvasHeight = max($canvasHeight, $height);

    $imgList[] = array('img' => $img, 'width' => $width, 'height' => $height);
  }

  $canvas = imagecreatetruecolor($canvasWidth, $canvasHeight);

  $x = 0;
  foreach ($imgList as $imgData) {
    imagecopy($canvas, $imgData['img'], $x, 0, 0, 0, $imgData['width'], $imgData['height']);
    $x += $imgData['width'];
  }

  // 保存结果图片到本地
  $resultFilename = uniqid() . '.jpg';
  imagejpeg($canvas, $resultFilename);

  // 释放资源
  imagedestroy($canvas);
  foreach ($imgList as $imgData) {
    imagedestroy($imgData['img']);
  }

  // 返回结果图片文件名
  die($resultFilename);
}
?>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>图片拼接工具</title>
</head>

<body>
  <input type="file" name="files[]" accept="image/*" multiple>
  <button id="operate-btn">拼接</button>
  <p id="result"></p>

  <script>
    const operateBtn = document.getElementById('operate-btn');
    const resultElem = document.getElementById('result');
    operateBtn.addEventListener('click', () => {
      const files = document.querySelector('input[name="files[]"]').files;
      if (files.length > 0) {
        const formData = new FormData();
        for (let i = 0; i < files.length; i++) {
          formData.append('files[]', files[i]);
        }
        fetch(location.href, {
            method: 'POST',
            body: formData
          })
          .then(response => response.text())
          .then(resultFilename => {
            resultElem.innerHTML = `
              <img src="${resultFilename}" alt="结果">
              <a href="${resultFilename}" download="result.jpg">下载结果图片</a>
            `;
          });
      } else {
        resultElem.innerHTML = '<p>请先选择要拼接的图片</p>';
      }
    });
  </script>
</body>

</html>

增加批量上传并拼接多张图片的示例代码:

这个示例将 PHP 代码和 HTML/JavaScript 代码组合在一起,实现了上传多张图片文件,并通过 PHP 对所有图片进行横向拼接,返回拼接后的结果图片文件名,使用 JavaScript 显示结果图片和下载结果图片的功能。

需要注意的是,这只是一个简单的示例代码,如需正式使用,还需要进行优化,例如添加文件格式校验、数据上传进度显示等功能。同时需要注意的是,该示例代码仅支持 PHP 7.0 及以上版本。

实例4:添加文件格式校验、数据上传进度显示 将多张图片所有的拼接在一起

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $files = $_FILES['files'];

  // 校验文件格式
  $allowTypes = array('image/jpeg', 'image/png', 'image/gif');
  foreach ($files['type'] as $type) {
    if (!in_array($type, $allowTypes)) {
      die('上传失败:只支持 jpeg、png 或 gif 格式的图片');
    }
  }

  // 检查是否上传成功
  foreach ($files['error'] as $error) {
    if ($error !== UPLOAD_ERR_OK) {
      die('上传失败');
    }
  }

  // 创建图片资源
  $canvasWidth = 0;
  $canvasHeight = 0;
  $imgList = array();
  foreach ($files['tmp_name'] as $i => $tmpName) {
    $img = imagecreatefromjpeg($tmpName);

    $width = imagesx($img);
    $height = imagesy($img);

    $canvasWidth += $width;
    $canvasHeight = max($canvasHeight, $height);

    $imgList[] = array('img' => $img, 'width' => $width, 'height' => $height);
  }

  $canvas = imagecreatetruecolor($canvasWidth, $canvasHeight);

  $x = 0;
  foreach ($imgList as $imgData) {
    imagecopy($canvas, $imgData['img'], $x, 0, 0, 0, $imgData['width'], $imgData['height']);
    $x += $imgData['width'];
  }

  // 保存结果图片到本地
  $resultFilename = uniqid() . '.jpg';
  imagejpeg($canvas, $resultFilename);

  // 释放资源
  imagedestroy($canvas);
  foreach ($imgList as $imgData) {
    imagedestroy($imgData['img']);
  }

  // 返回结果图片文件名
  die($resultFilename);
}
?>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>图片拼接工具</title>
</head>

<body>
  <input type="file" name="files[]" accept="image/*" multiple>
  <button id="operate-btn">拼接</button>
  <p id="result"></p>

  <script>
    const operateBtn = document.getElementById('operate-btn');
    const resultElem = document.getElementById('result');
    operateBtn.addEventListener('click', () => {
      const files = document.querySelector('input[name="files[]"]').files;
      if (files.length > 0) {
        const formData = new FormData();
        for (let i = 0; i < files.length; i++) {
          formData.append('files[]', files[i]);
        }

        const xhr = new XMLHttpRequest();

        // 上传进度监听
        xhr.upload.onprogress = (event) => {
          const progressPercent = (event.loaded / event.total) * 100;
          resultElem.innerHTML = `上传中... ${progressPercent.toFixed(0)}%`;
        };

        xhr.open('POST', location.href);
        xhr.send(formData);

        xhr.onload = () => {
          if (xhr.status === 200) {
            resultElem.innerHTML = `
              <img src="${xhr.responseText}" alt            ="结果">
              <a href="${xhr.responseText}" download="result.jpg">下载结果图片</a>
            `;
          } else {
            resultElem.innerHTML = '<p>拼接失败</p>';
          }
        };
      } else {
        resultElem.innerHTML = '<p>请先选择要拼接的图片</p>';
      }
    });
  </script>
</body>

</html>

新增部分包括了对文件格式进行校验,和上传进度的监听器。如果上传成功,显示的是上传文件进度百分比,成功后则显示结果图片,展示下载链接。如果上传失败,则会在结果区域显示提示信息。

需要注意的是,文件格式校验仅能对后缀与 MIME 匹配的格式进行判断,因此并不能完全防止用户上传非图片格式的文件。而上传进度监听器依赖于浏览器和服务器的支持,可能不适用于某些特殊情况。

实例5:多张两两横向拼接,删除源图片,成功的图片增加批量导出

<?php

$allowed_extensions = array("png", "jpg", "jpeg", "bmp");
$upload_dir = "comeimg/upload/";
$result_dir = "comeimg/result/";

if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0755, true);
}

if (!is_dir($result_dir)) {
    mkdir($result_dir, 0755, true);
}

if (isset($_POST['delete_result'])) { // 如果被点击了“删除结果”按钮,则删除结果目录里所有的图像
    $result_files = glob($result_dir . '*'); // 列出目录中符合条件的所有文件
    foreach ($result_files as $file) {
        unlink($file); // 删除文件
    }
    echo "All result images have been deleted!\n";
}

if (!empty($_FILES)) {
    $images = array();
    foreach ($_FILES["files"]["name"] as $key => $name) {
        $tmp_name = $_FILES["files"]["tmp_name"][$key];
        $error = $_FILES["files"]["error"][$key];
        $extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));

        if (!in_array($extension, $allowed_extensions)) {
            die("Error: Only " . implode(", ", $allowed_extensions) . " images are allowed.");
        }
        if ($error !== UPLOAD_ERR_OK) {
            die("Error uploading " . $name . ": " . $error);
        }
        list($width, $height) = getimagesize($tmp_name);
        if ($width <= 0 || $height <= 0) {
            die("Error: The image " . $name . " has invalid dimensions.");
        }
        $images[] = array(
            "path" => $tmp_name,
            "width" => $width,
            "height" => $height
        );
    }

    if (!empty($images)) {
        $chunked_images = array_chunk($images, 2);  // 将图像按两个一组拆分

        foreach ($chunked_images as $group_index => $image_group) {
            $total_width = array_sum(array_column($image_group, "width"));
            $max_height = max(array_column($image_group, "height"));
            $result_image = imagecreatetruecolor($total_width, $max_height);
            imagealphablending($result_image, false);
            imagesavealpha($result_image, true);
            $current_x = 0;
            foreach ($image_group as $image) {
                switch ($extension) {
                    case "png":
                        $temp_image = imagecreatefrompng($image["path"]);
                        break;
                    case "jpg":
                    case "jpeg":
                        $temp_image = imagecreatefromjpeg($image["path"]);
                        break;
                    case "bmp":
                        $temp_image = imagecreatefromwbmp($image["path"]);
                        break;
                }
                if (!$temp_image) {
                    die("Error: could not create image from file " . $image["path"]);
                }
                // 自动调整高度以适应最大的高度
                $temp_ratio = $max_height / $image["height"];
                $temp_x = $current_x + ($image["width"] * $temp_ratio);
                if (!imagecopyresampled($result_image, $temp_image, $current_x, 0, 0, 0, $temp_x - $current_x, $max_height, $image["width"], $image["height"])) {
                    die("Error: could not combine image " . $image["path"] . " with the result image.");
                }
                $current_x = $temp_x;
                imagedestroy($temp_image);
            }

            $result_file = $result_dir . "result_" . ($group_index + 1) . ".jpg";
            if (!imagejpeg($result_image, $result_file)) {
                die("Error: could not save the combined image file as " . $result_file);
            }
            echo "The result image for group " . ($group_index + 1) . " was successfully exported to <a href='" . $result_file . "' download> " . $result_file . "</a>!<br>";
            imagedestroy($result_image);
        }

    } else {
        echo "No images were uploaded to be combined!\n";
    }
}
?>



<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Image Merger</title>
</head>
<body>
	<h1>Image Merger</h1>
	<form method="POST" enctype="multipart/form-data">
		<legend>Upload Images to Merge:</legend>
		<input type="file" name="files[]" multiple required>
		<input type="submit" value="Combine Images">
		
	</form>
	<form method="post">
    <input type="submit" name="delete_result" value="Delete results">
</form>
	
</body>
</html>

实例6:多张两两纵向拼接,删除源图片,成功的图片增加批量导出

<?php

/**
 * Template name: widemerger纵向拼接
 */

get_header();



$allowed_extensions = array("png", "jpg", "jpeg", "bmp");


$upload_dir = get_template_directory() . '/myupload/mytool/picset/comeimg/upload/';  
$result_dir = get_template_directory() . '/myupload/mytool/picset/comeimg/result/';
$result_dirlink =  '/wp-content/themes/dux5.1/myupload/mytool/picset/comeimg/result/';


if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0755, true);
}

if (!is_dir($result_dir)) {
    mkdir($result_dir, 0755, true);
}

if (isset($_POST['delete_result'])) { // 如果被点击了“删除结果”按钮,则删除结果目录里所有的图像
    $result_files = glob($result_dir . '*'); // 列出目录中符合条件的所有文件
    foreach ($result_files as $file) {
        unlink($file); // 删除文件
    }
    echo "所有图片已删除!\n";
}

if (!empty($_FILES)) {
    $images = array();
    foreach ($_FILES["files"]["name"] as $key => $name) {
        $tmp_name = $_FILES["files"]["tmp_name"][$key];
        $error = $_FILES["files"]["error"][$key];
        $extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));

        if (!in_array($extension, $allowed_extensions)) {
            die("Error: Only " . implode(", ", $allowed_extensions) . " images are allowed.");
        }
        if ($error !== UPLOAD_ERR_OK) {
            die("Error uploading " . $name . ": " . $error);
        }
        list($width, $height) = getimagesize($tmp_name);//这句也是按坐标排序宽度和高度的
        if ($width <= 0 || $height <= 0) {
            die("Error: The image " . $name . " has invalid dimensions.");
        }
        $images[] = array(
            "path" => $tmp_name,
            "width" => $width,
            "height" => $height
        );
    }

    if (!empty($images)) {
        $chunked_images = array_chunk($images, 2);  // 将图像按两个一组拆分

        foreach ($chunked_images as $group_index => $image_group) {
            $total_height = array_sum(array_column($image_group, "height"));
            $max_width = max(array_column($image_group, "width"));
            $result_image = imagecreatetruecolor($max_width , $total_height );  //注意这个位置按横纵坐标排序的
            imagealphablending($result_image, false);
            imagesavealpha($result_image, true);
            $current_y = 0;  //这个合并坐标,x是横向,y坐标纵向  下面依次修改
            foreach ($image_group as $image) {
                switch ($extension) {
                    case "png":
                        $temp_image = imagecreatefrompng($image["path"]);
                        break;
                    case "jpg":
                    case "jpeg":
                        $temp_image = imagecreatefromjpeg($image["path"]);
                        break;
                    case "bmp":
                        $temp_image = imagecreatefromwbmp($image["path"]);
                        break;
                }
                if (!$temp_image) {
                    die("Error: could not create image from file " . $image["path"]);
                }
                // 自动调整宽度以适应最大的宽度  处理图片
                $temp_ratio = $max_width / $image["width"];
                $temp_y = $current_y + ($temp_ratio * $image["height"]);
                if (!imagecopyresampled($result_image, $temp_image, 0, $current_y, 0, 0, $max_width,$temp_y - $current_y,  $image["width"], $image["height"])) {
                    die("Error: could not combine image " . $image["path"] . " with the result image.");
                }
                $current_y = $temp_y;
                imagedestroy($temp_image);
            }

            $result_file = $result_dir . "result_" . ($group_index + 1) . ".jpg";
            $result_filelink = $result_dirlink . "result_" . ($group_index + 1) . ".jpg";
            if (!imagejpeg($result_image, $result_file)) {
                die("Error: could not save the combined image file as " . $result_file);
            }
            echo "拼接成功:图片分组 " . ($group_index + 1) . " 成功保存! <a href='" . $result_filelink . "' download> " .☞点击下载. "</a>!<br>";
            imagedestroy($result_image);
        }

    } else {
        echo "No images were uploaded to be combined!\n";
    }
}
?>






<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Image Merger</title>
	
	<style>  
    .centered-div {  
      display: flex;  
      justify-content: center;  
       
      
    }  
  </style>
	
	
	
</head>
<body>
    
    
    
	<h1 align="center">两两图片纵向拼接-自动分组</h1>
		<div class="centered-div"> 
	<form method="POST" enctype="multipart/form-data">
		<legend>第①步上传图片?:</legend>
		<input type="file" name="files[]" multiple required>
		</br>	</br>
		
		<legend>第②步拼接图片?:</legend>
		<input type="submit" value="开始拼接">
		</br>	</br>
		
	</form>
	 </div>
	 	</br>	</br>
	 <div class="centered-div"> 
	<form method="post">
	    <legend>第③步下载后及时删除图片保护隐私?:</legend>
    <input type="submit" name="delete_result" value="删除结果">
</form>
</div>
	
</body>
</html>

imagecopyresampled() 函数是在 PHP 中用来复制图像并重新调整其尺寸的。这个函数的参数详解如下:

  1. $result_image:目标图像,即你要将复制的图像粘贴到这个图像上。
  2. $temp_image:源图像,即你要从哪个图像复制数据。
  3. 0, $current_y:目标图像的起始坐标,表示粘贴位置的 x 和 y 坐标。
  4. 0, 0:源图像的起始坐标,表示从哪个位置开始复制图像。
  5. $max_width:目标图像的新宽度。
  6. tempy​−current_y:目标图像的新高度。这里看起来是想要每张图片的高度适应 max_width,然后根据图片数量决定总高度。
  7. $image[“width”]:源图像的宽度。
  8. $image[“height”]:源图像的高度。

这个函数会从源图像中抠出与目标图像等大的区域(如果存在的话),然后将该区域内的像素复制到目标图像的相应位置上。如果源图像和目标图像的尺寸不同,那么该函数会根据一些特定的算法重新调整像素的尺寸以适应目标图像。

一号优惠 · 51福利网薅羊毛福利具有时效性,如已失效,请留言
文章名称:《图片自动拼接的php代码》-一号优惠 · 51福利网
免责申明:本站所有活动信息均来自网络,如有失效、违规、不实或侵权,请联系我们删除。谢谢

评论 抢沙发

一号优惠经验分享网最新最全薅羊毛,现金红包线报网

一号优惠经验分享网提供每日最新内部优惠,薅羊毛活动,现金红包领取,免费福利和网赚福利手机赚钱线报,打造中国最受欢迎的网赚信息发布平台!51福利网

51联盟线报群赚钱·合作·帮助

登录

找回密码

注册