使用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
$imgfile toStorage::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
publicstorage disk is properly configured inconfig/filesystems.phpand that thestorage/app/public/uploadsdirectory exists with write permissions.
内容的提问来源于stack exchange,提问作者user9818065
相关产品推荐
相关产品推荐

