上传到服务器时,图像文件的大小会增加



我正在为laravel 使用InterventionImage

以下是我的图像上传功能,第一个是定期上传,第二个是调整大小

public function saveImage(Request $request, $requestField, $path)
{
if ($request->hasFile($requestField)) {
$image_path = public_path($this->{$requestField});
if (File::exists($image_path)) {
File::delete($image_path);
}
$file = $request->file($requestField);
$uploadname = $this->getUploadName($file);
$pathFull = public_path($path);
if (!File::exists($pathFull)) {
File::makeDirectory($pathFull, 0775, true);
}
$replaced = str_replace('_', '-', $requestField);
Image::make($file)->save($pathFull.$replaced .'-'. $uploadname);
$this->{$requestField} = $path.$replaced .'-'. $uploadname;
return $file;
}
return false;
}
public function copyImage($file, $requestField, $path, $width, $heigth)
{
$image_path = public_path($this->{$requestField});
if (File::exists($image_path)) {
File::delete($image_path);
}
$uploadname = $this->getUploadName($file);
$pathFull = public_path($path);
if (!File::exists($pathFull)) {
File::makeDirectory($pathFull, 0775, true);
}
$replaced = str_replace('_', '-', $requestField);
Image::make($file)->fit($width, $heigth, function ($constraint) {
$constraint->upsize();
})->save($pathFull.$replaced .'-'. $uploadname);
return $path.$replaced .'-'. $uploadname;
}

但事实证明,假设我上传了一个文件大小为200KB的图像,在服务器上它变成了400KB的

它可能与InterventionImage包的使用有关,还是可能是其他原因?

根据文档,您可以使用encode()方法更改保存图像的压缩级别。数字(0-100(表示"0";"质量";其中更高的数字将占用更多的字节。因此,像这样的东西应该有助于减少文件大小;您需要进行实验,找出最适合您需求的级别。

Image::make($file)
->fit($width, $heigth, fn ($constraint) => $constraint->upsize())
->encode('jpg', 75)
->save($pathFull . $replaced . '-' . $uploadname);

相关内容

  • 没有找到相关文章

最新更新