How to remove background in images using intervention image - php

I'm trying to remove the white background in logos to get a transparent icon, for example
on this image
Is .jpg, I want to remove withe background (Only what's outside if is possible, otherwise removing all the white background)
I'm trying using laravel intervention image with this code
public function resizeImage($logo, $placeName, $domain)
{
$mask = Image::make($logo)
->contrast(100)
->contrast(50)
->trim('top-left', null, 40)
->invert(); // invert it to use as a mask
$new_image = Image::canvas($mask->width(), $mask->height(), '#000000')
->mask($mask)
->resize(32,32, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
})
->encode('png', 100);
$route = $domain . '/favicon/favicon.png';
Storage::disk('gcs')
->put($route, $new_image);
$route = Storage::disk('gcs')
->url($route);
return $route;
}
but this is my result
the image lost color (black colored)
what am I doing wrong? I feel that I am very close to achieving it, however, I need the icons to have color

$img = Image::canvas(800, 600);
Call canvas method without background color.
See more on http://image.intervention.io/api/canvas

Related

Watermark Font Text Overlay Sizing issue with Laravel 8

Using Demo file from https://www.positronx.io/laravel-add-text-overlay-watermark-on-image-tutorial/
Have Installed Intervention/Image and config/app.php along with routes all working fine.
It will change the Font color and Font position but not the Font size
Not sure where the fonts are loaded - Be good to use a TT font but don't know where to store the uploaded font - I'm a novice with Laravel/Intervention and need specific path/folderforfont/ in LaravelApp
public function imageFileUpload(Request $request)
{
$this->validate($request, [
'file' => 'required|image|mimes:jpg,jpeg,png,gif,svg|max:4096',
]);
$image = $request->file('file');
$input['file'] = time().'.'.$image->getClientOriginalExtension();
$imgFile = Image::make($image->getRealPath());
$imgFile->text('© 2016-2020 positronX.io - All Rights Reserved', 120, 100, function($font) {
$font->size(35);
$font->color('#ffffff');
$font->align('center');
$font->valign('bottom');
$font->angle(90);
})->save(public_path('/uploads').'/'.$input['file']);
return back()
->with('success','File successfully uploaded.')
->with('fileName',$input['file']);
}
}
found this works with minimum code addition
upload ttf font to /public folder - eg RobotoMono-VariableFont_wght.ttf
then add below $imageFile-text line
$font->file(public_path('RobotoMono-VariableFont_wght.ttf'));
Simple when you know how - My Thanks to https://onlinewebtutorblog.com/how-to-add-watermark-text-on-images-laravel-8/

Laravel Azure Blob Storage Cache Images

this is my scenario:
I have a Laravel 6.x application and I'm using the FlySystemAzureBlobStorage package to store images on Azure Blob Storage.
Then I want to use the InterventionImageCache package to get and cache the images for faster client's downloads in different sizes.
I've already done it in this way:
public static function getImageResponseForApi($storageDiskName, $imagePath, $width = null, $height = null)
{
//check if the image exists on disk
$exists = empty($storageDiskName) ?
Storage::exists($imagePath) :
Storage::disk($storageDiskName)->exists($imagePath);
if ($exists) {
$image = empty($storageDiskName) ?
Storage::get($imagePath) :
Storage::disk($storageDiskName)->get($imagePath);
if (!empty($width) || !empty($height)) {
//use the image cache function to get the cached image if exists
$image = \Image::cache(function ($ima) use ($image, $width, $height) {
//check if height and with are higher than original or not
$ima->make($image)->resize($width, $height, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
});
}
$sizes = getimagesizefromstring($image);
$headers = [
'Content-Length' => strlen($image),
'Content-Type' => $sizes["mime"]
];
return \Response::make($image, 200, $headers);
} else {
return null;
}
}
There is a problem working in this way: I must download the image from azure blob storage before the system can check if a resized cached version of it exists.
The Azure package i'm using doesn't provide the possibility to get the image paths, so I can't find another solution to my problem.
So, is there a way to achieve the image caching without I have to download the file every time?
I use a separate route for showing/caching the image in my blade.
I store the image as BLOB in MYSQL PRODUCT table identified by product_id
BLADE:
<img src="/dbimage/{{$product->id}}.png" >
ROUTE:
Route::get('/dbimage/{id}',[ProductImageController::class, 'getImage']);
CONTROLLER:
class ProductImageController extends Controller
{
public function getImage($prodcutImageID){
$productID=explode(".",$prodcutImageID);
$rendered_buffer= Product::all()->find($productID[0])->image;
$response = Response::make($rendered_buffer);
$response->header('Content-Type', 'image/png');
$response->header('Cache-Control','max-age=2592000');
return $response;
}
}
This makes the browsers cache the images

resize and replace image using PHP

I am trying to resize and replace an image uploaded by the user but the most I can do is resize and output as another file. I have used the library image magician to resize.
If someone can explain how I can do it without using the library it would be better.
public function add() {
$f=Base::instance()->get('FILES');
$fext=pathinfo ($f['usrimg']['name'],PATHINFO_EXTENSION);
$this->copyFrom('POST');
$this->save();
$newName=str_pad($this->_id,5,"0").'.'.$fext;
move_uploaded_file($f['usrimg']['tmp_name'], $newName);
$this->load('id='.$this->_id);
$this->set('photo',$newName);
$this->update();
require_once('php_image_magician.php');
$magicianObj = new imageLib($newName);
$magicianObj->resizeImage(100, 200);
$magicianObj->saveImage('q.jpg', 100);
}
If you want to use gd library, for example you can use this code for resizing jpeg images:
$image=file_get_contents('image.jpg');
$src=imagecreatefromstring($image);
$x=imagesx($src);
$y=imagesy($src);
$y1=100; //new width
$x1=intval($y1*$x/$y); //new height proprtional to new width
$dst=imagecreatetruecolor($x1,$y1);
imagecopyresized($dst,$src,0,0,0,0,$x1,$y1,$x,$y);
header("Content-Type: image/jpeg");
imagejpeg($dst);

define a Route to show images via timthumb php script in laravel

I want to have a Route that takes image Dimension and source and return Cropped and resized image via timthumb php script.
I put timthumb.php file in a folder in public directory and I wrote this Route:
Route::get('/showImage/{w}/{h}/{src}', function ($w , $h , $src) {
$img = 'public/plugins/timthumb/timthumb.php?src='.$src.'&w='.$w.'&h='.$h;
return Response::make($img, 200, array('Content-Type' => 'image/jpeg'));
})->where('src', '[A-Za-z0-9\/\.\-\_]+');
But nothing happen.
How can I access to timthumb.php file and send it required parameters and get result image?
Update:
this is structure of Public directory and placement of timthumb and images folder :
According to , I try :
$img = 'public/plugins/timthumb/timthumb.php?src=../../'.$src.'&w='.$w.'&h='.$h;
And :
$img = 'public/plugins/timthumb/timthumb.php?src=public/'.$src.'&w='.$w.'&h='.$h;
But none of them does not work for bellow URL:
http://localhost:8000/showImage/100/200/upload/slideshow/slide2.jpg
I suggest using league/glide. Watch Using Glide in Laravel to get started.
The better way to use timthumb image in Laravel using intervention/image
Install this package.
Update your Route:
Route::get('showImage/{w}/{h}/{src}', function ($w , $h , $src)
{
$img_path = public_path().'/'.$src;
$img = Image::make($img_path)->resize($w, $h);
return $img->response('jpg');
})->where('src', '[A-Za-z0-9\/\.\-\_]+');
OR Image Cache
Install intervention/imagecache package
Route::get('showImage/{w}/{h}/{src}', function ($w , $h , $src)
{
$img_path = public_path().'/'.$src;
$img = Image::cache(function($image)use($w,$h,$img_path) {
return $image->make($img_path)->resize($w, $h);
});
return Response::make($img, 200, ['Content-Type' => 'image/jpeg']);
})->where('src', '[A-Za-z0-9\/\.\-\_]+');
Image URL would be as below:
http://<< Domain Name >>/showImage/800/400/Desert.jpg

Resizing an image before displaying it in the browser

I'm creating an API in which I have a model called OnlineAds(), it has these columns title, full_discription, short_discription and image, I also created an input form to fill in these fields and upload an image, in the image field I add the image's name and store the image in this path: storage/uploads. I was able to retrieve the image and display it, but I still didn't figure out how to resize it before displaying (lets say I want it to be 300 x 300), can anybody show me how ?
Note: I tried to use Stapler and Imagine but they seemed to give multiple bugs and failed!
This is my controller:
public function show()
{
$img = OnlineAds::find(50)->image;
$path = storage_path('uploads') . '/' . $img;
if (File::exists($path)) {
$filetype = File::type($path);
$response = Response::make(File::get($path), 200);
$response->header('Content-Type', $filetype);
return $response;
}
}
You could look into using Intervention to take care of the image processing as well as handling the response. It can be as easy as this:
public function show()
{
$img = OnlineAds::find(50)->image;
$path = storage_path('uploads') . '/' . $img;
if (File::exists($path)) {
$img = Image::make($path);
$img->resize(300, 300);
return $img->response();
}
}
There are detailed instructions on how to install the Intervention library and integrate it with Laravel, and it shouldn't take more than a few minutes to get it up and running.

Categories