Storing an HTMLCanvasElement as a JPG in Laravel - laravel

I have integrated a cropping script that returns either an image or an HTMLCanvasElement in my Vue Component. In my component's crop method, I then make an axios post call to my upload function. Here is the crop method:
crop() {
var croppedCanvas = this.cropper.getCroppedCanvas()
var img = croppedCanvas.toDataURL('image/jpeg', 1.0);
var formData = new FormData();
formData.append('image', img) // I can send croppedCanvas here too if I want
axios.post('/api/upload', formData)
}
Now the problem. I can't seem to save the HTMLCanvasElement or the Image as a JPG file. I tried so many different approaches (toDataURL, toBlob, etc.) and have failed in every single one. My latest implementation was as follows:
public function upload(Request $request) {
$input = $request->all();
$img = $input['image'];
Storage::put('picture.jpg', $img);
return response(Response::HTTP_OK);
}
This saves a 26 byte file in the storage/public folder which is unaccessible.
Can someone please help with how to go about this.
I simply want to save the HTMLCanvasElement as a JPG file in my storage/public folder.
Thanks.

Actually as mentioned in the docs over here : https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL
toDataURL method returns back a base64 encoded data so you have to decode it on the server side
you can use the base64_decode method in laravel like this
public function upload(Request $request) {
$img = $request->image;
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
Storage::put('picture.jpg', $data);
return response(Response::HTTP_OK);
}

Related

How to choose were Image Intervention should store the images?

Im trying to save a resized copy of an image that has been uploaded, but Image Interventions doesent seem to know in what root directory to begin in, or maybe it is just me that dosent know how to configure it propertly.
This is my code in AvatarImageController#store
public function store(Request $request, Game $game)
{
if ($request->hasFile('game_image')) {
$request->validate([
'game_image' => 'mimes:jpeg,png|max:1014'
]);
$file = $request->file('game_image');
$filename_thumbnail = "thumb_". $file->hashName();
$path_full = $request->file('game_image')->store('images/test_folder');
$path_thumb = $request->file('game_image')->storeAs('images/test_folder/thumbs', $filename_thumbnail);
// resize image
$path_thumb = Intervention::make("./storage/app/public/" . $path_thumb)->resize(300, 200);
$path_thumb->save();
$image = new Image;
$image->full = basename($path_full);
$image->thumb = $filename_thumbnail;
$game->images()->save($image);
return back()->with('success', "Success!! Image uploaded.");
}else{
return back()->with('success', 'Ooops.. something went wrong.');
}
abort(500, 'Could not upload image :(');
}
The error i receive:
Intervention\Image\Exception\NotReadableException
Image source not readable
I suspect this is because im not in the correct path, because of these lines from above function:
// resize image
$path_thumb = Intervention::make("./storage/app/public/" . $path_thumb)->resize(300, 200);
$path_thumb->save();
And it is a real hassel working with explicit paths when using git as deployment.
You can make image directly like this:
$uploadedFile = $request->file('game_image');
$image = Image::make($uploadedFile);
Resize it:
$image = $image->resize(300, 200);
and save it like this:
$image_data = $image->encode('jpg')->__toString();
$relative_file_path = 'images/test_folder/';
Storage::put($relative_file_path, $image_data)
use the storage() helper?
Intervention::make(storage_path('app/public/") . $path_thumb)

Convert image to webp after adding watermark on image

I am currently working on a project on which I have to add watermark to image and then convert the image into webp format.I come up with two libraries to do so but they both require uploaded image as parameters, but after adding watermark the input for the webp library becomes object of Image Intervention.
This is my Laravel Controller Code
use Illuminate\Http\Request;
use File;
use Webp;
use Intervention\Image\ImageManagerStatic as Image;
public function store(Request $request)
{
foreach ($request->image as $img) {
$destinationPath = 'uploads/auction';
$watermark = 'uploads/auction/logo.png';
$originalFile = $img->getClientOriginalName();
$filename= uniqid().'-'.time().'-image.jpg';
$name = $destinationPath.'/'.$filename;
$img = Image::make($img);
$img = $img->insert($watermark, 'bottom-right', 1, 1);
$img->save($name);
WebP::make($img)->save($name);
}
}
Can anyone provide me a solution to achieve this??

Laravel Image source not readable error

I am working on uploading a video locally and then use it locally to upload to s3. It successfully uploads to s3 but I get this error:
Image source not readable
/var/www/yt/vendor/intervention/image/src/Intervention/Image/AbstractDecoder
I found this error when I was trying to delete the image after I uploaded it to s3. I think it is the reason the delete does not work. How do I fix the error?
public function avatar(Request $request)
{
$imageData = $request->get('image');
$img = Image::make($request->get('image'))->fit(300)->encode('jpg');
// calculate md5 hash of encoded image
$hash = md5($img->__toString());
// use hash as a name
$path = "avatars/{$hash}.jpg";
// save it locally
$test = $img->save(storage_path($path));
// $url = "/images/{$hash}.jpg"
$url_local = $path;
$path = Storage::putFile('avatars', new File(storage_path($url_local)));
if($path){
//TODO make into event
Storage::disk('local')->delete(storage_path($url_local));
// \Debugbar::error($test);
}
$user = User::find(Auth::id());
$user->avatar_url = $path;
if ($user->save()) {
return response()->json(['avatar' => $user->gen_avatar()]);
}
}

Laravel intervention/image doesn't resize image

I am trying to use laravel intervention plugin. I installed it without problem but can't use it.
I am trying to make a test function which returns resized image, but without success;
I think the problem may be in image path, please help me fix my code.
function test($img)
{
/* $img = Image::make('public/image1.jpg');
$img->resize(300, 200);
return $img; */
$image = Image::make('http://localhost/cms/digital-cms/public/image1.jpg')->resize(200, 200, function ($c) {
$c->aspectRatio();
$c->upsize();
});
return $image;
//$h=200; $w=200;
//return Image::make(public_path('public/image1.jpg')->resize($h, $w)->response('jpg'));
}
//get image
$image=$request->file('image');
//rename image
$input = time().'.'.$image->getClientOriginalExtension();
//your directory to upload
$destinationPath = 'main/images/company';
//save and resize image
$img = Image::make($image->getRealPath());
$img->resize(20,20, function ($constraint) {
$constraint->aspectRatio();
})->save($destinationPath.'/'.$input);
You should use response function on Image class to return the image
$image = Image::make('http://localhost/cms/digital-cms/public/image1.jpg')->resize(200, 200, function ($c) {
$c->aspectRatio();
$c->upsize();
});
return $image->response();
In my case, I was resizing, cropping (fit) but the final image is still the same as original. Found out that I had to add function encode, to produce the manipulated image
return $image->encode('jpg', 80);

how to encode image decoded by base64_decode, symfony

I have a image decode by base64_decode.
I have a entity Image. This is entity consist : id and path to the file. File of image load to server by this guide http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html.
How encode this string and upload file to server and upload path to database in controller.
my controller
public function updateattachmentAction()
{
$em = $this->getDoctrine()->getManager();
$photo = $em->getRepository('MyPluginBundle:Photo')->findOneById(4);
$str="";
$request = $this->container->get('request');
$image = $request->query->get('image');
// file_put_contents($photo, base64_decode($data));
// $photo->upload();
// $em->persist($photo);
// $em->flush();
$response = array("code" => 100,"success" => true);
//you can return result as JSON
return new Response(json_encode($response));
}
it should help DataUriNormalizer
https://symfony.com/blog/new-in-symfony-3-1-data-uri-normalizer## Heading ##
use Symfony\Component\Serializer\Normalizer\DataUriNormalizer;
$normalizer = new DataUriNormalizer();
$avatar = $normalizer->denormalize('data:image/gif;base64,R0lGODdhAQABAIAAAP///////ywAAAAAAQABAAACAkQBADs=', 'SplFileObject');
// $avatar is a SplFileObject with the GIF image contents
and this https://github.com/hshn/base64-encoded-file
use Hshn\Base64EncodedFile\HttpFoundation\File\Base64EncodedFile;
$file = new Base64EncodedFile(base64_encode($data));
$file->getPathname(); // "/path/to/file"
$file instanceof Symfony\Component\HttpFoundation\File\File; // true

Resources