Php 调整大小后显示图像
我正在尝试使用以下功能调整大小和图像:Php 调整大小后显示图像,php,gd,Php,Gd,我正在尝试使用以下功能调整大小和图像: function resize_image($file, $w, $h, $crop=FALSE) { list($width, $height) = getimagesize($file); $r = $width / $height; if ($crop) { if ($width > $height) { $width = ceil($width-($width*abs($r-$w
function resize_image($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*abs($r-$w/$h)));
} else {
$height = ceil($height-($height*abs($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
创建函数后,我尝试使用以下代码在调整大小后显示图像,但它不起作用:
<?php
$img = resize_image('../images/avatar/demo.jpg', 120, 120);
var_dump($img); //The result is: resource(6, gd)
?>
<img src="<?php echo $img;?>"/>
"/>
PS:包含该功能没有问题您不能以这种方式直接输出图像。您可以:
<?php
$img = resize_image('../images/avatar/demo.jpg', 120, 120);
imagejpeg($img, '../images/avatar/demo-resized.jpg');
?>
<img src="<?= 'www.example.com/images/avatar/demo-resized.jpg' ?>"/>
"/>
方法2:
<?php
$img = resize_image('../images/avatar/demo.jpg', 120, 120);
ob_start();
imagejpeg($img);
$output = base64_encode(ob_get_contents());
ob_end_clean();
?>
<img src="data:image/jpeg;base64,<?= $output; ?>"/>
"/>
您用来存储图像的指令在哪里,或者您想“动态”调整图像大小?您只是试图打印一个图像资源标识符,希望获得一个图像,这是行不通的…您可能需要一个文件夹来存储您调整大小的临时图像,并在完成其功能后删除它们。