gpt4 book ai didi

php - 如何使为调整图像大小而编写的代码适用于各种图像扩展并对其进行优化?

转载 作者:可可西里 更新时间:2023-11-01 13:11:07 27 4
gpt4 key购买 nike

基本上,我为我的网站使用 PHP 和 HTML。我是 PHP 的新手。因此,如果我在我的代码或方法中犯了任何错误,我请求您纠正我。

我已经编写了将用户上传的图像调整为特定大小(即特定宽度和高度)的代码。我想让上传的图片尺寸为940 px * 370 px。但是在这样做的同时我想处理以下问题:

  1. 修改尺寸后保存到服务器的图像的整体质量应与用户上传的图像相同。它不应收缩或拉伸(stretch),它的原始颜色不应受到干扰等。图像的所有内容应保持原样,但尺寸应在 940 px * 370 px 范围内。。
  2. 不应将黑色背景添加到保存在服务器上的图像中。
  3. 该代码应该适用于所有标准图像格式。也就是说,如果用户上传的图像是任何标准图像格式,则应该重新调整大小,否则不会。

为了实现上述功能,我编写了以下代码:

HTML 代码(upload_file.html):

<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

PHP 代码(upload_file.php):

<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 5242880)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/upload" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
//Store the name of the temporary copy of the file stored on the server
$images = $_FILES["file"]["tmp_name"];

/*Create a new file name for uploaded image file :
*prepend the string "upload" to it's original file name
*/
$new_images = "upload".$_FILES["file"]["name"];


//Copies a file contents from one file to another
//copy($_FILES["file"]["tmp_name"],"upload/".$_FILES["file"]["name"]);

$width = 940;

//Determine the size of a given image file and return the dimensions along with the file type
$size=GetimageSize($images);

//$height=round($width*$size[1]/$size[0]);

$height = 370;

//Create a new image from file or URL & returns an image identifier representing the image obtained from the given filename.
$images_orig = ImageCreateFromJPEG($images);

//Get image width of originally uploaded image
$photoX = ImagesX($images_orig);

//Get image height of originally uploaded image
$photoY = ImagesY($images_orig);

$scaleX = $width / $photoX;
$scaleY = $height / $photoY;
$scale = min($scaleX, $scaleY);

$scaleW = $scale * $photoX;
$scaleH = $scale * $photoY;

/*$width = $scale * $photoX;
$height = $scale * $photoY;*/

//Create a new true color image & returns an image identifier representing a black image of the specified size.
$images_fin = ImageCreateTrueColor($width, $height);

$background = ImageColorAllocate($images_fin, 0, 0, 0);

ImageFill($images_fin, 0, 0, $background);

/*Copy and resize part of an image with resampling
*copies a rectangular portion of one image to another image,
*smoothly interpolating pixel values so that, in particular,
*reducing the size of an image still retains a great deal of clarity.
*/
/*ImageCopyResampled($images_fin, $images_orig, 0, 0, 0, 0, $width+1, $height+1, $photoX, $photoY);*/
ImageCopyResampled($images_fin, $images_orig, $width / 2 - $scaleW / 2, $height / 2 - $scaleH / 2, 0, 0, $scaleW+1, $scaleH+1, $photoX, $photoY);

/*Output image to browser or file
*creates a JPEG file from the given image.
*/
ImageJPEG($images_fin,"upload/".$new_images);

/*Destroy an image
*frees any memory associated with image image.
*/
ImageDestroy($images_orig);
ImageDestroy($images_fin);

echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
} else {
echo "Invalid file";
}
?>

注意:要测试上面的代码并查看上传的图像,请在文件 upload_file.html 和 upload_file.php 所在的同一目录中创建一个名为“上传”的文件夹,并具有适当的权限。

实际上,上面的代码对我有用,但它有以下几个问题:

  1. 它对扩展名为 .jpg 的图像文件发出警告。它不应该发生。
  2. 图片在修改尺寸后保存到服务器 (940 px * 370px)。保存到服务器的图像质量与用户上传的原始图像质量相同,但它在图像背景中添加了额外的黑色空间。它不应该发生。

您可以通过上传尺寸高于 940 像素 * 370 像素 且大小不超过 5 MB 的图像来检查本地计算机上的代码功能。 p>

如果有人能帮助我解决以上两个问题,那将对我有很大帮助。

最佳答案

回答你的第一个问题

It's giving warnings for image files with extensions other than .jpg. It should not happen.

您收到警告是因为您使用 JPEG 特定函数打开图像,无论格式如何:

// line 48
$images_orig = ImageCreateFromJPEG($images);

要解决此问题,您可以使用通用的 imagecreatefromstring 函数,它可以在不考虑图像格式的情况下打开图像。

// line 48
$images_orig = ImageCreateFromString(file_get_contents($images));

资源:


回答你的第二个问题

the image is saving to the server after modifications in it's dimensions (940 px * 370px). The quality of image saved to the server is same as of original image uploaded by user but it's adding additional black space in the background to the image. It should not happen.

这里有两个错误:

  • 您在重新采样图像时未指定目标 gd 图像应支持透明度
  • 您正在将结果保存为 JPEG,但 JPEG 不支持透明度。

您正在对图像重新采样,但未指定目标 gd 图像应支持透明度。

要实现它,您应该首先在目标图像中选择透明颜色:我习惯使用浅粉色 (#FF00FF) 作为透明,因为这不是图像上常见的颜色(如果您要上传花卉图片,选择另一种颜色 :-))。然后,在将源图像复制到目标图像之前,将背景颜色设置为浅粉色:整个图像将变得透明而不是黑色。

替换:

     // line 67
$images_fin = ImageCreateTrueColor($width, $height);

$background = ImageColorAllocate($images_fin, 0, 0, 0);

ImageFill($images_fin, 0, 0, $background);

通过以下几行:

     $images_fin = ImageCreateTrueColor($width, $height);

$transparent = ImageColorAllocate($images_fin, 255, 0, 255);
ImageFill($images_fin, 0, 0, $transparent);
ImageColorTransparent($images_fin, $transparent);

您将结果保存为 JPEG,但是 JPEG does not support transparency .

要解决这个问题,只需更换:

     // line 31
$new_images = "upload" . $_FILES["file"]["name"];
// line 85
ImageJPEG($images_fin, "upload/" . $new_images);
// line 93
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];

通过:

     // line 31
$new_images = "upload" . $_FILES["file"]["name"] . '.png';
// line 85
ImagePNG($images_fin, "upload/" . $new_images);
// line 93
echo "Stored in: " . "upload/" . $new_images;

资源:


您的代码,包含上述修复

<?php

$allowedExts = array ("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);

if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 5242880) && in_array($extension,
$allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/upload" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
//Store the name of the temporary copy of the file stored on the server
$images = $_FILES["file"]["tmp_name"];

/* Create a new file name for uploaded image file :
* prepend the string "upload" to it's original file name
*/
$new_images = "upload" . $_FILES["file"]["name"] . '.png';


//Copies a file contents from one file to another
//copy($_FILES["file"]["tmp_name"],"upload/".$_FILES["file"]["name"]);

$width = 940;

//Determine the size of a given image file and return the dimensions along with the file type
$size = GetimageSize($images);

//$height=round($width*$size[1]/$size[0]);

$height = 370;

//Create a new image from file or URL & returns an image identifier representing the image obtained from the given filename.
$images_orig = ImageCreateFromString(file_get_contents($images));

//Get image width of originally uploaded image
$photoX = ImagesX($images_orig);

//Get image height of originally uploaded image
$photoY = ImagesY($images_orig);

$scaleX = $width / $photoX;
$scaleY = $height / $photoY;
$scale = min($scaleX, $scaleY);

$scaleW = $scale * $photoX;
$scaleH = $scale * $photoY;

/* $width = $scale * $photoX;
$height = $scale * $photoY; */

//Create a new true color image & returns an image identifier representing a black image of the specified size.
$images_fin = ImageCreateTrueColor($width, $height);
$transparent = imagecolorallocate($images_fin, 255, 0, 255);
imagefill($images_fin, 0, 0, $transparent);
imagecolortransparent($images_fin, $transparent);

/* Copy and resize part of an image with resampling
* copies a rectangular portion of one image to another image,
* smoothly interpolating pixel values so that, in particular,
* reducing the size of an image still retains a great deal of clarity.
*/
/* ImageCopyResampled($images_fin, $images_orig, 0, 0, 0, 0, $width+1, $height+1, $photoX, $photoY); */
ImageCopyResampled($images_fin, $images_orig, $width / 2 - $scaleW / 2, $height / 2 - $scaleH / 2, 0, 0,
$scaleW + 1, $scaleH + 1, $photoX, $photoY);

/* Output image to browser or file
* creates a JPEG file from the given image.
*/
ImagePNG($images_fin, "upload/" . $new_images);

/* Destroy an image
* frees any memory associated with image image.
*/
ImageDestroy($images_orig);
ImageDestroy($images_fin);

echo "Stored in: " . "upload/" . $new_images;
}
}
}
else
{
echo "Invalid file";
}

enter image description here

关于php - 如何使为调整图像大小而编写的代码适用于各种图像扩展并对其进行优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26311993/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com