尝试使用PHP调整图像大小
有人知道这个代码有什么问题吗?它不是给我一个真实的图像,而是给我一个图像错误。我想我把所有的功能都设置正确了。任何建议都会很棒尝试使用PHP调整图像大小,php,Php,有人知道这个代码有什么问题吗?它不是给我一个真实的图像,而是给我一个图像错误。我想我把所有的功能都设置正确了。任何建议都会很棒 <?php function resizeImage($filename, $max_width, $max_height) { list($orig_width, $orig_height) = getimagesize($filename); $width = $orig_width; $height = $orig_height; # t
<?php
function resizeImage($filename, $max_width, $max_height) {
list($orig_width, $orig_height) = getimagesize($filename);
$width = $orig_width;
$height = $orig_height;
# taller
if ($height > $max_height) {
$width = ($max_height / $height) * $width;
$height = $max_height;
}
# wider
if ($width > $max_width) {
$height = ($max_width / $width) * $height;
$width = $max_width;
}
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0,
$width, $height, $orig_width, $orig_height);
return $image_p;
}
$directory = "uploads/";
$images = glob($directory."*");
foreach($images as $image) {
// Set a maximum height and width
$width = 200;
$height = 200;
$newImage = resizeImage($image, $width, $height);
echo '<img src="'.$newImage.'" /><br />';
}
?>
如果不想保存图像,可以使用以下代码
<?php
function resizeImage($filename, $max_width, $max_height) {
list($orig_width, $orig_height) = getimagesize($filename);
$width = $orig_width;
$height = $orig_height;
# taller
if ($height > $max_height) {
$width = ($max_height / $height) * $width;
$height = $max_height;
}
# wider
if ($width > $max_width) {
$height = ($max_width / $width) * $height;
$width = $max_width;
}
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $orig_width, $orig_height);
ob_start();
imagejpeg($image_p);
$imgSrc = 'data:image/jpeg;base64,'.base64_encode(ob_get_clean());
return $imgSrc;
}
$directory = "uploads/";
$images = glob($directory."*");
foreach($images as $image) {
// Set a maximum height and width
$width = 200;
$height = 200;
$imgSrc = resizeImage($image, $width, $height);
echo '<img src="'.$imgSrc.'" /><br />';
}
?>
哦,我是否必须将调整大小的图像保存到某个位置?如果必须只显示一个图像,则不需要。但在这里,您在同一页中显示了多个图像。@JaeKim:如果您不想保存图像,请检查我的答案。
$imgSrc='data:image/jpeg;base64'.base64_编码(ob_get_clean())代码>这是否有效?是,它获取当前缓冲区内容并删除当前输出缓冲区。
<?php
$directory = "uploads/";
$images = glob($directory."*");
$i=1;//added
foreach($images as $image) {
// Set a maximum height and width
$width = 200;
$height = 200;
$newImage = resizeImage($image, $width, $height);
imagejpeg($newImage,"resized/newimage".$i.".jpg"); //added
echo '<img src="resized/newimage'.$i.'.jpg" /><br />';//modified
$i++;//added
}
?>