Having problems with creating image cache with Intervention \ Image - laravel

So heres my code
public static function getImageThumb($link) {
$domain = substr(Request::root(), 7);
if(starts_with(Request::root(), 'http://')) {
$domain = substr(Request::root(), 7);
}
$link = $domain.$link; // This is prety much something like this domain.name/uploads/image/13_0.jpeg
$img = Image::cache(function ($image) use ($link) {
return $image->make($link)->resize(230, 140);
}, 5, true);
return $img;
}
And it gives me this:
Intervention \ Image \ Exception \ NotReadableException
Image source not readable
I dont really know whats wrong here..
Thanks for help!
EDIT-------------------------
I fixed it like this:
public static function getImageThumb($link) {
$link = trim($link, '/');
$img = Image::cache(function ($image) use ($link) {
return $image->make($link)->resize(230, 140);
}, 5, true);
return $img;
}
But how do i get the link to img now? So i can place it in src for img tag.

If you're going to use a URL as the source parameter for the make method, make sure it includes the scheme as well, or it will consider it to be a local file path. So get rid of the part where you strip the http:// from the URL, just use:
public static function getImageThumb($link)
{
$link = Request::root() . $link;
$img = Image::cache(function ($image) use ($link) {
return $image->make($link)->resize(230, 140);
}, 5, true);
return $img;
}
Also, since the image not from a remote domain, it makes more sense to just read it from the filesystem, instead of making a HTTP request for it:
public static function getImageThumb($link)
{
$path = public_path() . $link;
$img = Image::cache(function ($image) use ($path) {
return $image->make($path)->resize(230, 140);
}, 5, true);
return $img;
}
To return the cached version of a image, you have to have a dedicated route that retrieves the resized image. Something like this should do:
Route::get('/images/{link}', function ($link)
{
// Repo will be the class implementing your getImageThumb method
$img = Repo::getImageThumb($link);
// This makes sure the HTTP response contains the necessary image headers
return $img->response();
});
Now in your blade Blade template file you generate the URL like so:
<img src="{{ asset('/images/' . $link) }}">
By prepending /images to the actual link path you're hitting the route that is going to use the image cache if it is available. So your links would now look like this:
http://domain.name/images/uploads/image/13_0.jpeg
instead of
http://domain.name/uploads/image/13_0.jpeg
Of course you can use anything you like as the path prefix, not necessarily /images.

Related

laravel Backpack Original Image Name

I am using laravel backpack for my site and i need to upload some images, i copy the code from their website and works fine, but i need the original name on the images, i tried some things, but is not working.
public function setImageAttribute($value)
{
$attribute_name = "image";
$disk = "uploads";
$destination_path = 'storage/services/' .date('FY').DIRECTORY_SEPARATOR;
if ($value==null) {
Storage::disk($disk)->delete($this->{$attribute_name});
// set null in the database column
$this->attributes[$attribute_name] = null;
}
if (str_starts_with($value, 'data:image'))
{
$file = $value;
$filename = $this->generateFileName($file, $destination_path);
$image = InterventionImage::make($file)->orientate();
$fullPath = $destination_path.$filename.'.'.$file->getClientOriginalExtension();
$this->attributes[$attribute_name] = $fullPath;
}
protected function generateFileName($file, $destination_path)
{
$filename = basename($file->getClientOriginalName(), '.'.$file->getClientOriginalExtension());
$filename = Str::random(20);
while (Storage::disk('uploads')->exists($destination_path.$filename.'.'.$file->getClientOriginalExtension())) {
$filename = Str::random(20);
}
return $filename;
}
why value alwys take image base64
is there any way to git image original name?
As far as I know, you won't be able to retrieve the filename, as it's always a base64 file. But maybe this work around helps you:
Image fields blade file can be found at:
\vendor\backpack\crud\src\resources\views\crud\fields\image.blade.php
You can overwrite it by making a file on the same name at:
\resources\views\vendor\backpack\crud\fields\image.blade.php
You can change anything there, maybe you can add a hidden input with the file name.

Intervention\Image\Exception\NotWritableException Can't write image data to path

I'm trying to put a image on a folder than i generate with a timestamp.
This give me the error in the title.
Intervention\Image\Exception\NotWritableException
Can't write image data to path (/Users/me/Sites/test/public/uploads/images/1573905600/title-1.jpg)
This is my code :
$photoPaths = $request->get('photo_paths');
if (isset($photoPaths)){
$photos = explode(';', $photoPaths);
$path = storage_path('tmp/uploads/');
$newPath = public_path('/uploads/images/').strtotime('12:00:00')."/";
$arrayPhoto = array();
foreach($photos as $photo){
$photoPath = $path . $photo;
if (File::exists($photoPath)) {
$newPhotoName = Str::slug($request->get('titre')."-".$i,"-").".jpg";
$newPhotoFullPath = $newPath . $newPhotoName;
$photo = Image::make($photoPath);
// $photo->resize(1400, 1050);
$photo->resize(null, 1050, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$photo->encode('jpg', 85);
if(!Storage::disk('public')->has($newPath)){
Storage::disk('public')->makeDirectory($newPath); //It seems it doesn't work
}
$saved = $photo->save($newPhotoFullPath); //Create the Exception
}
}
}
What i am doing wrong ?
Thanks
check this that this folder is already created or not.
then give it permission to write
sudo chmod -R 666 /public/upload/images //give permission your choice either it 666 or 775 or 777
and
$newPath = public_path('/uploads/images/').strtotime('12:00:00')."/";
if (!file_exists($newPath)) {
mkdir($newPath, 0755);
}
Check out this line of code
$newPhotoName = Str::slug($request->get('titre')."-".$i,"-").".jpg";
is it suppose to be
$newPhotoName = Str::slug($request->get('title')."-".$i,"-").".jpg";
I mean $request->get('title') instead of $request->get('titre').
OR
You can check out your input name from blade against your request validation and also your model fillable if they are same.
I hope this helps.

I need webp image on Opencart 3. It is possible?

Is it possible to use webp images in opencart 3? I mean automatic generation.
Not all the browsers accept WEBP image format
but you can type a code to check if the browser accept WEBP format then you will have to make a new images cache and convert the existing images to webp
on the fir dir catalog/model/tool/image.php
add
$image_new_webp = 'cachewebp/' . utf8_substr($filename, 0, utf8_strrpos($filename, '.')) . '-' . (int)$width . 'x' . (int)$height . '.webp';
after this
$image_new = 'cache/'
to check if the browser accept image.webp and to create your new images cache
in the same file: catalog/model/tool/image.php
add this code:
$gd = gd_info();
if ($gd['WebP Support']) {
if (!is_file(DIR_IMAGE . $image_new_webp) || (filectime(DIR_IMAGE . $image_new) > filectime(DIR_IMAGE . $image_new_webp))) {
$path = '';
$directories = explode('/', dirname($image_new_webp));
foreach ($directories as $directory) {
$path = $path . '/' . $directory;
if (!is_dir(DIR_IMAGE . $path)) {
#mkdir(DIR_IMAGE . $path, 0777);
}
}
$image_webp = new Image(DIR_IMAGE . $image_old);
$image_webp->resize($width, $height);
$image_webp->save_webp(DIR_IMAGE . $image_new_webp);
}
}
before this line: $image_new = str_replace(
now you need a function to save the images in new format
on file dir: system/library/image.php
add this function:
public function save_webp($file, $quality = 90) {
if (is_resource($this->image)) {
imagewebp($this->image, $file, $quality);
imagedestroy($this->image);
}
}
before this line: public function save($file, $quality = 90) {
output the webp images format
add this function on file system/library/response.php
public function webpRebuild($output) {
$gd = gd_info();
if ($gd['WebP Support']) {
$uri = '';
if (isset($_SERVER['REQUEST_URI'])) {
$uri = $_SERVER['REQUEST_URI'];
}
if (stripos($uri, 'admin') === false) { // admin is your dashboard url if you have different name jst change it
if (isset($_SERVER['HTTP_ACCEPT']) && isset($_SERVER['HTTP_USER_AGENT'])) {
if( strpos( $_SERVER['HTTP_ACCEPT'], 'image/webp' ) !== false ) {
$re = '/(cache)(.*)(\.jpg|\.png|.jpeg)/U';
$subst = '$1webp$2.webp';
$this->output = preg_replace($re, $subst, $this->output);
}
}
}
}
}
before this line: private function compress($data, $level = 0)
on the same file you have to output the webpRebuild function so add this code:
$this->webpRebuild($this->output);
after this line: $output = $this
Search the OpenCart extension marketplace for "webp":
https://www.opencart.com/index.php?route=marketplace/extension&filter_search=webp
Here are a couple, both free:
https://www.opencart.com/index.php?route=marketplace/extension/info&extension_id=36308
https://www.opencart.com/index.php?route=marketplace/extension/info&extension_id=34275
The best solution is at Design Cart. The extension generates additional webp images and displays them if the user's browser supports webp. Download.

Dynamic filter with liipImagineBundle

I'm using liipImagineBundle and am trying to apply a filter directly into a controller.
In the doc I found two sections in which explains how to use liipImagineBundle from the controller. This one https://github.com/liip/LiipImagineBundle#using-the-controller-as-a-service
public function indexAction()
{
// RedirectResponse object
$imagemanagerResponse = $this->container
->get('liip_imagine.controller')
->filterAction(
$this->getRequest(),
'uploads/foo.jpg', // original image you want to apply a filter to
'my_thumb' // filter defined in config.yml
);
// string to put directly in the "src" of the tag <img>
$srcPath = $imagemanagerResponse->headers->get('location');
// ..
}
And https://github.com/liip/LiipImagineBundle/blob/master/Resources/doc/filters.md#dynamic-filters
public function filterAction(Request $request, $path, $filter)
{
$targetPath = $this->cacheManager->resolve($request, $path, $filter);
if ($targetPath instanceof Response) {
return $targetPath;
}
$image = $this->dataManager->find($filter, $path);
$filterConfig = $this->filterManager->getFilterConfiguration();
$config = $filterConfig->get($filter);
$config['filters']['thumbnail']['size'] = array(300, 100);
$filterConfig->set($filter, $config);
$response = $this->filterManager->get($request, $filter, $image, $path);
if ($targetPath) {
$response = $this->cacheManager->store($response, $targetPath, $filter);
}
return $response;
}
I tested as indicated in "Using the controller as a service" and it works, the problem I have is that I don't know how to access the filter settings to modify it.
liip_imagine:
driver: gd
web_root: %kernel.root_dir%/../web
data_root: %kernel.root_dir%/../web
cache_mkdir_mode: 0777
cache_prefix: /media/cache
cache: web_path
cache_clearer: true
data_loader: filesystem
controller_action: liip_imagine.controller:filterAction
formats: []
filter_sets:
my_thumb:
filters:
crop: { start: [0, 0], size: [200, 150] }
my_paste:
quality: 90
filters:
paste: { start: [30, 60], image: ../web/uploads/images/firma.jpg }
The second, really, I don't understand when he says "With a custom data loader...".
In the example he is only modifying the method filteraction() from the ImagineController class (Liip\ImagineBundle\Controller). I wonder how I can modify that method dynamically? For example from my controller indexAction().
Also i have read this post https://stackoverflow.com/questions/16166719/loading-your-custom-filters-with-liipimaginebundle where #NSCoder says that "You can use the built in filter and modify their configuration." but i don't understand it.
I've been looking for several days but I haven't found an example from which to start.
Looking for some more I found another LiipImagineBundle topic (Use LiipImagineBundle to Resize Image after Upload?) that has helped me to do what I wanted..
here I leave the code I use to dynamically apply a filter
public function indexAction()
{
$container = $this->container;
# The controller service
$imagemanagerResponse = $container->get('liip_imagine.controller');
# The filter configuration service
$filterConfiguration = $container->get('liip_imagine.filter.configuration');
# Get the filter settings
$configuracion = $filterConfiguration->get('my_thumb');
# Update filter settings
$configuracion['filters']['crop']['size'] = array(50, 150);
$configuracion['filters']['crop']['start'] = array(10, 10);
$filterConfiguration->set('my_thumb', $configuracion);
# Apply the filter
$imagemanagerResponse->filterAction($this->getRequest(),'uploads/images/logo.jpg','my_thumb');
# Move the img from temp
$fileTemporal = new File('media/cache/my_thumb/uploads/images/logo.jpg');
$fileTemporal->move('uploads/images/', 'mini-logo.jpg');
####################################
}

Get original image url Magento (1.6.1.0)

I have the following piece of code:
$cProduct = Mage::getModel("catalog/product");
foreach($products_id as $product_id) {
$product = $cProduct->load($product_id);
//$products_image[] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).str_replace(Mage::getBaseUrl('media'),"", $product);
//$products_image[] = $product->getMediaConfig()->getMediaUrl($_product->getData('image'));
$products_image[] = $product->getImageUrl(); //product's image url
}
As you can see, I've tried several ways to get the original image url. Currently I'm using getImageUrl(), but it retrieves the base image, which is a cropped version. How can I retrieve the original image??
Thanks in advance.
Edit:
Seriously appears there isn't a function for it, been Googling for hours straight (also before posting here). So I've written my own function.
function get_original_image_url($base_image_url) {
$exploded = explode("/", $base_image_url);
$image_name = $exploded[count($exploded) - 1];
$original_image_url = "http://yoursitehere.com/media/catalog/product/" . $image_name[0] . "/" .
$image_name[1] . "/" . $image_name;
return $original_image_url;
}
I call it with:
$original = get_original_image_url($product->getImageUrl());
Works for me, though it isn't a nice way to do it.
You should use the catalog product media config model for this purpose.
<?php
//your code ...
echo Mage::getModel('catalog/product_media_config')
->getMediaUrl( $product->getImage() ); //getSmallImage(), getThumbnail()
Hope this helps.
Other faster way:
$cProduct = Mage::getModel("catalog/product");
$baseUrl = Mage::getBaseUrl('media') . 'catalog/product/';
foreach($products_id as $product_id) {
$product = $cProduct->load($product_id);
$products_image[] = $baseUrl . $product->getImage();
}

Resources