所以我有一个php文件,它接收一个图像文件并返回一个图像文件。问题是它在我期待文件时返回一个字符簇。我该如何解决?对不起,我是Php的新手。
所以我在标题中设置内容类型并使用此方法imagejpeg($ newImage);
<?php
error_reporting(0);
$newSize = $_POST['newSize'];
if(empty($newSize)){
header("Status: 400 Bad Request", true, 400);
exit();
}
$extension = strtolower(strrchr($_FILES['image']['name'], '.'));
$imageInfo = getimagesize($_FILES['image']['tmp_name']);
switch($extension){
case '.jpg':
case '.jpeg':
$image = imagecreatefromjpeg($_FILES['image']['tmp_name']);
break;
case '.gif':
$image = imagecreatefromgif($_FILES['image']['tmp_name']);
break;
case '.png':
$image = imagecreatefrompng($_FILES['image']['tmp_name']);
break;
default:
header("Status: 400 Bad Request", true, 400);
exit('');
}
$newImage = imagecreatetruecolor($newSize, $newSize);
if(empty($newImage) || empty($image)){
header("Status: 400 Bad Request", true, 400);
exit();
}
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newSize, $newSize, $imageInfo[0], $imageInfo[1]);
header('Content-Type: ' . $imageInfo['mime']);
switch($extension){
case '.jpg':
case '.jpeg':
imagejpeg($newImage);
break;
case '.gif':
imagegif($newImage);
break;
case '.png':
imagepng($newImage);
break;
}
?>
答案 0 :(得分:0)
未经测试,但这可行。它将初始化文件下载。如果您发布的代码是您自己的代码,那么您应该将其添加到其中。
<?php
error_reporting(0);
$newSize = $_POST['newSize'];
if(empty($newSize)){
header("Status: 400 Bad Request", true, 400);
exit();
}
$extension = strtolower(strrchr($_FILES['image']['name'], '.'));
$imageInfo = getimagesize($_FILES['image']['tmp_name']);
switch($extension){
case '.jpg':
case '.jpeg':
$image = imagecreatefromjpeg($_FILES['image']['tmp_name']);
break;
case '.gif':
$image = imagecreatefromgif($_FILES['image']['tmp_name']);
break;
case '.png':
$image = imagecreatefrompng($_FILES['image']['tmp_name']);
break;
default:
header("Status: 400 Bad Request", true, 400);
exit('');
}
$newImage = imagecreatetruecolor($newSize, $newSize);
header('Content-Type: '.$_FILES['image']['type']);
header('Content-Disposition: attachment; filename="image'.$extension.'"');
switch($extension){
case '.jpg':
case '.jpeg':
imagejpg($newImage);
break;
case '.gif':
imagegif($newImage);
break;
case '.png':
imagepng($newImage);
break;
}
if(empty($newImage) || empty($image)){
header("Status: 400 Bad Request", true, 400);
exit();
}