如何在将产品图像存储到Laravel的数据库中之前调整产品图像的大小?



我想在将图像存储在数据库中之前调整图像大小。我想存储带有一些产品信息的产品图像。我已经编写了下面的代码,但图像大小仍然保持不变..如何在代码中解决此问题?

public function store(Request $request)
{
$product=new Product();
$request->validate([
'product_name' => 'required|max:255',
'product_title' => 'required|max:255',
'category'=>'required|integer',
'subcategory'=>'required|integer',
'product_code' => 'required',
'product_price' => 'required',
'product_discount' => 'integer',
'product_color' => 'max:255',
'product_price'=>'required',
'product_size'=>'max:255',
'homepage_visiblity'=>'max:255',
'homepage_trend'=>'max:255',
'product_description' =>'required|max:1000',
'image' => 'required|file|image|max:5000',
]);
$image=$request->file("image");
if($image){

$image_name=str_random(20);
$ext=strtolower($image->getClientOriginalExtension());
$image_full_name=$image_name.'.'.$ext;
$upload_path='image/';
$image_url=$upload_path.$image_full_name;
$image_resize =Image::make($image->getRealPath());              
$image_resize->resize(20, 100);
$image->move($upload_path,$image_full_name);
$product->image=$image_url;

$product->product_name=$request->product_name;
$product->product_title=$request->product_name;
$product->category_id=$request->category;
$product->subcategory_id=$request->subcategory;
$product->product_code=$request->product_code;
$product->product_price=$request->product_price;
$product->product_discount=$request->product_discount;
$product->product_color=$request->product_color;
$product->product_price=$request->product_price;
$product->product_size=$request->product_size;
$product->homepage_visiblity=$request->homepage_visiblity;
$product->hot_trend =$request->hot_trend;

$product->save();
Session::put('message','Product inserted successfully!!!!');
return redirect('/product');
}

}

我相信您需要在调整大小后保存图像。如果您同意覆盖原始图像文件,请尝试以下操作:

$img = Image::make($image->getRealPath())->resize(20, 100)->save();

如果您不想覆盖原始图像文件,请尝试此操作;

$img = Image::make($image->getRealPath())->resize(320, 240)->save('public/foo.png');

"public/foo.png"应更改为相对于应用程序根目录所需的位置

...
if($request->hasFile('image'))
{
$image = $request->file('image');
$ext = strtolower($image->getClientOriginalExtension());
$fileNewName = str_random(20) . ".{$ext}";
$destination = "image";
$successUpload = $image->move($destination, $fileNewName);
if($successUpload)
{
Image::make($destination . '/' . $fileNewName)->resize(20, 100)->save();
}
$product->image = $fileNewName;
...
}

最新更新