You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Intervention包压缩图片无效,图片大小未改变

Fix for Intervention Image Not Compressing Images

The issue here is that you're creating the compressed image instance but never actually using it—you're still storing the original uploaded file instead of the compressed version. Here's how to fix it:

Corrected Controller Code

<?php 

namespace App\Http\Controllers; 

use Intervention\Image\ImageManagerStatic as Image; 
use Illuminate\Support\Facades\Storage; 
use Illuminate\Http\Request; 

class UploadsController extends Controller { 
    public function store() { 
        // Get the uploaded image file
        $img = request()->file('img'); 

        // Create and compress the image
        $compressedImage = Image::make($img)->encode('jpg', 1); 

        // Store the compressed image (use a proper filename to avoid overwrites)
        $filePath = 'uploads/' . $img->hashName();
        Storage::disk('public')->put($filePath, $compressedImage->get()); 

        // Optional: Return the stored path for your application to use
        return response()->json(['stored_path' => $filePath]);
    } 
}

Key Fixes Explained

  • Capture the compressed image: We assign the result of Image::make($img)->encode('jpg', 1) to $compressedImage—this variable holds your resized, compressed image data.
  • Store the right data: Instead of passing the original $img file to Storage::put(), we use $compressedImage->get() to save the actual compressed content.
  • Valid filename: Added $img->hashName() to generate a unique, safe filename (you can replace this with $img->getClientOriginalName() if you want to keep the original filename, but be cautious of duplicates).

Quick Additional Tips

  • If you want to support multiple image formats dynamically, replace 'jpg' with $img->getClientOriginalExtension() in the encode method.
  • Double-check that your public storage disk is properly configured in config/filesystems.php and that the storage/app/public/uploads directory exists with write permissions.

内容的提问来源于stack exchange,提问作者user9818065

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:04:58