有人知道这段代码有什么问题吗?它不是给我一个实际的图像,而是给我一个图像错误。我想我正确地设置了所有功能和一切。任何建议都很棒。
<?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 />';
}
?>
答案 0 :(得分:1)
如果您不想保存图像,则可以使用以下代码。
<?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 />';
}
?>
如果你想保存图像,那么你必须创建一些其他文件夹,如resized
,并在那里保存裁剪的图像并将其链接如下所示。(不要更改旧代码并添加此)
<?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
}
?>