如果您的 php 脚本返回原始图像数据,那么您可以通过 src 链接到它,尽管扩展名为 .php,但浏览器会将其识别为图像(也因为图像标题):
<img src="http://www.test.com/myImageScript.php">
另一种方法是,如果您对图像的内容进行编码并返回没有任何标头的 base64 编码字符串。来自旧项目的一些代码可能会有所帮助。
<?php
$outputs = array('raw','base_64');
if(isset($_GET['source']) && strlen($_GET['source']) > 0 && isset($_GET['w']) && is_numeric($_GET['w']) && isset($_GET['h']) && is_numeric($_GET['h']) && isset($_GET['out']) && in_array($_GET['out'], $outputs))
{
$imgPath = trim(urldecode($_GET['source']));
if(file_exists($imgPath))
{
include 'simpleImage.php';
$w = $_GET['w'];
$h = $_GET['h'];
$out = $_GET['out'];
processImage($imgPath, $w, $h, $out);
}
}
function processImage($img, $w, $h, $out)
{
thumb($img, $w, $h, $out);
}
/*
* BASE_64 image data
*/
function data_uri($contents, $mime)
{
$base64 = base64_encode($contents);
return ('data:' . $mime . ';base64,' . $base64);
}
/*
* Get mime type of file
*/
function getMIME($filename)
{
if(function_exists('mime_content_type') && $mode==0)
{
$mimetype = mime_content_type($filename);
return $mimetype;
}
elseif(function_exists('finfo_open') && $mode==0)
{
$finfo = finfo_open(FILEINFO_MIME);
$mimetype = finfo_file($finfo, $filename);
finfo_close($finfo);
return $mimetype;
}
}
/*
* Create image
*/
function thumb($data, $w, $h, $out = 'raw')
{
$image = imagecreatefromstring(file_get_contents($data));
$thumb_width = $w;
$thumb_height = $h;
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect )
{
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}
else
{
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 10, // 2 = Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
if($out == 'raw')
{
header('Content-Type: image/jpeg');
imagejpeg($thumb);
}
elseif($out == 'base_64')
{
ob_start();
imagejpeg($thumb);
$thumbImageData = ob_get_contents();
$thumbImageDataLength = ob_get_length();
ob_end_clean();
echo '<img src="' . data_uri($thumbImageData, getMIME($data)) . '">';
}
}
?>