Home > database >  Image file size increases when uploading to the server
Image file size increases when uploading to the server

Time:12-21

I am using the Intervention\Image package for laravel

Here are my image upload functions, the first is a regular upload, the second is a resize

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;
}

But it turns out that, let's say I upload an image with a file size of 200KB, and on the server it becomes 400KB

Could it be related to the use of the Intervention\Image package or could it be something else?

CodePudding user response:

According to the documentation, you can use the encode() method to vary compression levels on the saved image. The number (0-100) indicates "quality" where a higher number will take up more bytes. So something like this should help reduce file size; you'll need to experiment to find out what level works best for your requirements.

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

CodePudding user response:

This is quite normal, if you increase image size than original size. Also, returning false is not good method of terminating code. Why do you need such a code?

  • Related