引言

一、iframe基础

1.1 iframe的基本用法

iframe元素允许您在HTML页面中嵌入另一个HTML页面。其基本语法如下:

<iframe src="url" width="300" height="200"></iframe>

其中,src属性指定要嵌入的页面URL,widthheight属性分别指定iframe的宽度和高度。

1.2 iframe的属性

iframe还有一些其他属性,如:

  • frameborder:设置iframe是否有边框。
  • scrolling:设置iframe是否显示滚动条。
  • allowtransparency:设置iframe是否支持透明背景。

二、PHP iframe图片上传显示

2.1 前端代码

<iframe id="imageIframe" src="upload.php" style="display:none;"></iframe>
<form action="upload.php" method="post" enctype="multipart/form-data">
  <input type="file" name="image" />
  <input type="submit" value="上传" />
</form>

2.2 后端代码

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $image = $_FILES['image'];
    $uploadDir = 'uploads/';
    $imagePath = $uploadDir . basename($image['name']);
    
    if (move_uploaded_file($image['tmp_name'], $imagePath)) {
        echo "<script>document.getElementById('imageIframe').src='" . $imagePath . "';</script>";
    } else {
        echo "图片上传失败!";
    }
}
?>

2.3 图片显示

三、实战案例解析与技巧分享

3.1 图片预览

<input type="file" id="fileInput" />
<img id="preview" src="" alt="图片预览" />
<script>
document.getElementById('fileInput').addEventListener('change', function() {
  const file = this.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = function(e) {
      document.getElementById('preview').src = e.target.result;
    };
    reader.readAsDataURL(file);
  }
});
</script>

3.2 图片压缩

function compressImage($imagePath, $quality) {
    $imageInfo = getimagesize($imagePath);
    switch ($imageInfo[2]) {
        case IMAGETYPE_JPEG:
            $image = imagecreatefromjpeg($imagePath);
            imagejpeg($image, $imagePath, $quality);
            break;
        case IMAGETYPE_PNG:
            $image = imagecreatefrompng($imagePath);
            imagepng($image, $imagePath, $quality);
            break;
        case IMAGETYPE_GIF:
            $image = imagecreatefromgif($imagePath);
            imagegif($image, $imagePath, $quality);
            break;
    }
    imagedestroy($image);
}

// 示例:压缩图片
compressImage($imagePath, 75);

3.3 多图上传

在实际应用中,我们可能需要支持多图上传。以下是修改后的PHP代码:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $uploadDir = 'uploads/';
    foreach ($_FILES['image']['name'] as $key => $name) {
        $imagePath = $uploadDir . basename($name);
        if (move_uploaded_file($_FILES['image']['tmp_name'][$key], $imagePath)) {
            echo "<script>document.getElementById('imageIframe').src='" . $imagePath . "';</script>";
        } else {
            echo "图片上传失败!";
        }
    }
}

四、总结