GithubHelp home page GithubHelp logo

matt-pawley / oc-imageresizer-plugin Goto Github PK

View Code? Open in Web Editor NEW
46.0 7.0 39.0 531 KB

October CMS Plugin to resize and compress images

Home Page: https://octobercms.com/plugin/toughdeveloper-imageresizer

License: MIT License

PHP 95.19% HTML 4.81%
image-resizer october-cms php image-compression

oc-imageresizer-plugin's People

Contributors

alxy avatar chocolata avatar cx-emerge avatar dieterholvoet avatar everyx avatar felixinx avatar gergo85 avatar linkapiotr avatar lthurston avatar luketowers avatar matt-pawley avatar matteotrubini avatar mattpawley avatar mauserrifle avatar multiwebinc avatar that0n3guy avatar yapsr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

oc-imageresizer-plugin's Issues

Thumb SEO name

Hi,

the resized images get this pretty "un-SEO" name (eg. thumb__300_300_0_0_crop.png). Is there a way to give this files nice SEO names (eg. my-coffee-machine__300_300_0_0_crop.png )? From maybe the slugified ALT or Title value?

Regard,
Darjan

Image not found

Hello! I'm on october CMS v2 (2.0.26).

Question:
Is the resize filter now in the core?

I installed the plugin, but I get "Image not found" placeholder. When I disable the plugin, the images aren't found either. I cleared the cache, but I get the same results.

Here's my code inside my plugins component:

<div class="board__image-container">
                <img src="{{ board.image.path|resize(180, 200) }}" alt="{{ board.image.file_name }}" class="board_image">
</div>

When I remove the resize filter, it all works fine.

Storage path error after update to OctoberCMS v3.1

After updating to v3.1 I had errors such as:

An exception has been thrown during the rendering of a template ("touch(): Unable to create file /home/xxxcom/wkyvhuazaq/public_html/storage/app/public/57b/ca3/a75/thumb__2000_0_0_0_auto.jpg because No such file or directory").

This was fixed by adding "uploads/" on line 115, 118 and 123:

    public function getCachedImagePath($public = false)
    {
        $filePath = $this->file->getStorageDirectory() . $this->getPartitionDirectory() . $this->thumbFilename;

        if ($public === true) {
            return url('/storage/app/uploads/' . $filePath);
        }

        return storage_path('app/uploads/' . $filePath);
    }

    protected function deleteTempFile()
    {
        $path = storage_path('app/uploads/' . $this->file->getStorageDirectory() . $this->getPartitionDirectory() . $this->file->disk_name);
        if (file_exists($path)) {
            unlink($path);
        }
    }

Temporary file is not deleted

I have the following file in my media folder:

-rw-rw-r-- 1 user user 4120619 Dec  4 09:05 images/IMG_0281.JPG

So I put the following in one of my views to use this image:

    <img src="{{ 'images/IMG_0281.JPG'|media|resize(600,600) }}">

This creates (in my case) the following directory tree in the uploads/public directory:

73f
└── [       4096]  fe6
    └── [       4096]  021
        ├── [    4120619]  73ffe6021b91d705a567bed46a2d7871
        └── [     107565]  thumb__600_600_0_0_auto.JPG

However as you notice here, the file 73ffe6021b91d705a567bed46a2d7871 is actually just the image (verified with md5sum). This needlessly doubles the storage space for the original full-size image. Instead only the thumbnail should be stored and the original image should be only in the original directory.

Resizing original image on upload

Hi,

Thanks for your fantastic plugin. I'm so glad it's out here, because it works great.

In my project I have a standard form in which people can upload 5 images. These images are stored as file attachment in System\Models\File. Right now I'm uploading the images in their original uncompressed form and resize them when they appear on the frontend, using the twig filter {{ '/path/to/image.jpg' | resize(250, 100) }}. This works great, but I'd like to compress the original images as well.

A nice rule I'm having in my head is forcing images not to exceed 1000 by 1000 pixels, and also running them by TinyPNG. This way, I'd save a lot of disk space, because I'm seeing images of 10MB+ in this project.

I've noticed we can use your plugin in PHP too. Is it possible to save the compressed image and to replace the original? Something like:

use ToughDeveloper\ImageResizer\Classes\Image;
use ThirdPartyDeveloper\CarManager\Models\Car;

// Create a new instance of car based on user input
$car= new Car();
$car->name = Input::get('car_name');
$car->save();

// Compress image
$image = new Image(Input::file('car_image'));
$image->resize(1000, 1000);

// Attach compressed image
 $car->images()->create(['data' =>$image]);

Would something like this be possible? I was experimenting with another plugin, but kept running into problems.

A second part of the question is: would we be able to do something like the linked plugin, where we compress images as soon as they appear in the media library?

What are your thoughts?
Thanks in advance.

Max width or max height for images

Hello,

I need to resize image that way :

  • It should never have a width more than 180px
  • It should never have a height more than 100px
  • Is should keep aspect ratio and not crop

I tested all provided modes but can't find a way to do that. I exclude "exact" and "crop" mode because of the third point, so there is "auto", "portrait" and "landscape"

The problem with landscape/portrait mode is that they resize picture just by looking the width/height value. So I can have picture of 2000x100px or 180x2000px.

I don't find any mode that can do what I need, could you please point me the right direction if a solution actually exist ?

here is my code :

image.jpg|media|resize(180, 100, { mode: '???' })

Issue with EDGE build 423

I'm testing some of my websites to see how they work on the laravel 5.5 version of octoberCMS (current build 423). You plugin does not seem te work in this version.
This is of course no problemen for now, I thought to mention is just in case you didn't notice it.

I love you're plugin!

Return image not found in localhost

Hi, Using

{% for image in post.featured_images|slice(0,1) %}
<a href="{{ post.url }}"><img src="{{ image.path | media | resize(100) }}" alt=""></a>
{% endfor %}

Returns always Image not found

Using media, theme or not filter I have the same result.

<img src="{{ image.path | media | resize(100) }}" alt="">
<img src="{{ image.path | theme | resize(100) }}" alt="">
<img src="{{ image.path | resize(100) }}" alt="">
<img src="{{ image.path | resize(100,100) }}" alt="">

Rendered thumbnail file has different filename than is output from the twig plugin

In other words, I'm rendering a thumbnail like this:

<img src="{{ year.hero_image | media | resize(538) }}" />

Which outputs this:

<img src="http://my.dev/storage/app/uploads/public/807/0db/830/thumb__538_0_0_0_auto.png">

But the file on disk is:

thumb__538x0_0_0_auto.png

I've managed to make it work by changing the the getThumbFilename() function to alter the filename template -- haven't had a change to dig in any further than that -- and it works.

Seems like an odd bug, unless there has been a change in thumbnail filename creation internally, and this plugin is mirroring / duplicating that code. I'll dig a little deeper tomorrow and see if I can find a better solution.

php 8 explode error

Hello,
under some circumstances on php 8.0 we can get this error:
explode(): Argument #1 ($separator) cannot be empty
I already fixed this i will make pull request soon.

How to display all attached images in list view?

Here is original code, little edited //Mediafinder part - original somehow did not work.

public function evalGalerylListColumn($value, $column, $record)
    {
        $config = $column->config;

        // Get config options with defaults
        $width = isset($config['width']) ? $config['width'] : 50;
        $height = isset($config['height']) ? $config['height'] : 50;
        $options = isset($config['options']) ? $config['options'] : [];

        // attachMany relation?
        if (isset($record['attachMany'][$column->columnName])) {
            $file = $value->first();
        }
        // attachOne relation?
        elseif (isset($record['attachOne'][$column->columnName])) {
            $file = $value;
        }
        // Mediafinder
        else {
            $file = $value->first();
        }

        $image = new Image($file);

        return $image->resize($width, $height, $options)->render();
    }

My question is how I can display all attached images not just first?

Media-Library & Spaces

Using the plugin with twig-filter | media causes an "Image not found" if the image-name contains a space-character.

The media filter HTML-encodes all URL-unsafe characters, causing space characters to be converted to %20. Therefore it is not possible to use the plugin in conjunction with the media-library.

Example-Code:
'path/to/image with a space.jpg' | media | resize()

Wrong paths are generated when installed in subfolder since build 467

Hi,

Recently there was an updated to how paths are generated by October CMS (build 467), causing installs in subfolders to have issues with generated paths from the | media filter. It seems the subfolder is left out the path.

Luke has mentioned a workaround here, by explicitly mentioning the subfolder in the path in the configuration:
octobercms/october#5204

This fixes the issue for the | media filter but it does not work for the Image Resize plugin.
The only workaround I have found is to set the 'linkPolicy' to 'force' in the cms.php configuration file.

Should we accommodate this?

oc-imageresizer-plugin is being migrated to core - https://github.com/octobercms/october/pull/5231

Hi all,
It sounds like @toughdeveloper is no longer able to invest the time necessary to maintain this project (see #53). I'm quite grateful to him for this plugin as my team uses it on most October projects, and see the need for it to live on beyond his maintenance of it.

I'm hoping someone who sees this message would be willing to take on the task of maintaining this plugin for us and for posterity. Unless, of course, there's some other plugin out there that does this better.

I would be willing to do so but I'm afraid I might quickly fall into the same situation that Matthew has, and might not be able to put the time into it that's required. However, I'd be happy to collaborate with a few other maintainers to keep this thing going.

Let's discuss!

Please note that so far I've only referred people to this message who have open PRs on the project. If we need to bring a larger group in, or have the conversation elsewhere (Slack), that's fine by me. I just want to get the ball rolling.

Lucas

Add another compressor support

TniyPNG is a great addon but it is a paid option which makes it difficult to use if you have many images on the website. I think you should implement a free library which will compress the the images and is as good as TinyPNG.

For this, I think resmush.it/ is a good candidate. Please look into it. I tried to integrate it with your library but I ran into some issues since I'm new to OctoberCMS and Laravel.

Try this link

Cannot install plugin Syntax error in version.yaml

When I try to install this plugin in October cms V3

php artisan plugin:install ToughDeveloper.ImageResizer

I get a syntax error during the php artisan october:migrate
stage

Executing: php artisan october:migrate

Migrating Application and Plugins

In Yaml.php line 43:

A syntax error was detected in /var/www/html/plugins/toughdeveloper/imageresizer/updates/version.yaml. The string "!!! Changes path to cached image for builds
of October 420+. Thanks to that0n3guy" could not be parsed as it uses an unsupported built-in tag at line 13 (near "1.3.5: !!! Changes path to cached image for
builds of October 420+. Thanks to that0n3guy") at line 43 (near "/var/www/html/vendor/october/rain/src/Parse/Yaml.php").

The line is line 13 in https://github.com/matt-pawley/oc-imageresizer-plugin/blob/develop/updates/version.yaml

1.3.5: !!! Changes path to cached image for builds of October 420+. Thanks to that0n3guy

Generate unique file cache key based on relative (not absolute) path

The issue is that with some deployment setups, the path to the latest release (with symlinks resolved) changes with each build. When this happens, the paths to all files on the site change too, meaning they get regenerated with each release.

The solution would be to determine if a file has been cached based on an MD5 of the original filename provided to the Image::__contruct() method, rather that the full disk name.

I've got a PR for this which I will submit shortly.

Error happens when use webp type image on server, but normal on local

Server environment: CentOS 7.2 LNMP
Local environment: Windows10 WNMP

example:
when use {{ 'assets/images/theme/bg-presence.webp'|theme }}, both server and local worked well.
when use {{ 'assets/images/theme/bg-presence.webp'|theme|resize(200,200) }}, server throws error, but local works well.

Error info:

# /www/wwwroot/octobercms/vendor/october/rain/src/Database/Attach/Resizer.php line 527

        break;
    case 'image/png':
        $img = @imagecreatefrompng($filePath);
        $this->retainImageTransparency($img);
        break;
    case 'image/webp':
        $img = @imagecreatefromwebp($filePath);               ##here line 527##
        $this->retainImageTransparency($img);
        break;
    default:
        throw new Exception(sprintf('Invalid mime type: %s. Accepted types: image/jpeg, image/gif, image/png, image/webp.', $this->mime));
        break;
}

image

Prevent/remove duplicate image

Look into minimise duplicated images (following feedback from Lilydale Heights College):

Very useful and practical utility. It gives some new opportunities in using Media Library and optimise media content. I use it a lot especially with TinyPNG. However, it has a peculiarity as well.

When using RainLab Blog you can apply getThumb to a featured image and you have your thumbs created in the same upload folder where your original file is stored.

The Image Resizer in this situation creates a new upload folder, copy the original in to it as a file without extension, then creates thumbs there.

As a result, you have 2 copies of the original file in different folders, double your file structure and used storage space. If your storage is limited, this feature becomes an issue. I am not sure if there is a good reason to keep the second copy of the original file.

The partial '_field_thumb.htm' is not found.

The README, under the heading Usage in Backend List, says:

The image resizer can also be used on backend lists with the type of thumb, e.g.

image:
	label: Image
	type: thumb

However, when I use it like this, i.e. adding such a field in a theme.yaml, I get this error when trying to edit the theme settings:

The partial '_field_thumb.htm' is not found.

Is the README wrong or have I misunderstood something?

I have the current version, 1.3.5 installed.

Add thumb type in model list of builder plugin

Hello,

I just saw that you can easily display images in backend using the thumb type and that's fantastic !

However, the builder plugin don't know this type and when you open the model list into the builder, it can't display any time in front of the image column.

Would be really great to alter that list to add the thumb type, so it would be directly selectable in the builder plugin

Get url of thumbnail image from code tab

Hello,

I'm trying to get a thumbnail image url in the code tab of my page, in order to generate an url for og:image meta tag.

I can create an image object using this code :

use ToughDeveloper\ImageResizer\Classes\Image;
$image = new Image($record->images[0]->path);
$image->resize(150, 200, ['mode' => 'crop']);

But then, I don't know how to retrieve the thumbnail url as a string.

Could you point me the best way to get it ?

Thanks

Alex

Same folder as original image

Hi,
Would it be possible to save the newly created thumb to the same folder as the original image ?
And while I'm here, I have another question:
How to delete the thumb when I delete the original image from for example an attachOneor attachMany relationship ?

Regards,
Alexis

Replaced images are not displayed

When replacing an image in the media manger the frontend still displays the old image.
php artisan cache:clear does not resolve the problem.

Image not found when URL contains %20

Images using following markup are not found

{{ record.preview_image_media | media | resize(125, 250, { mode: 'crop'}) }}

When orignal image path contains URL with %20 in it
/storage/app/media/image%20Default.jpg

How to use the images resizer in the RainLab.Blog plugin?

Great plugin!
I am wondering if it is possible to use this in the Rainlab.Blog with using the Markdown language?
If yes, how can I do this?
If not. are there any plans for it?

The Markdown setup for images in the blog:
![alt-text-here](/storage/app/media/name-of-the-image.jpg "Title Will be Here"){.class #div}

Wrong url in templates

When using the |resize(X,X) filter the url generated in the template uses the following structure
image

But when I look at the stored image it uses the following structure:
image

I got it working by changing the code in Image.php

/**
     * Generates a thumbnail filename.
     * @return string
     */
    protected function getThumbFilename($width, $height)
    {
        $width = (integer) $width;
        $height = (integer) $height;
        
        return 'thumb__' . $width . 'x' . $height . '_' . $this->options['offset'][0] . '_' . $this->options['offset'][1] . '_' . $this->options['mode'] . '.' . $this->options['extension'];
    }

with

/**
     * Generates a thumbnail filename.
     * @return string
     */
    protected function getThumbFilename($width, $height)
    {
        $width = (integer) $width;
        $height = (integer) $height;
        
        return 'thumb__' . $width . '_' . $height . '_' . $this->options['offset'][0] . '_' . $this->options['offset'][1] . '_' . $this->options['mode'] . '.' . $this->options['extension'];
    }

file_exists(): open_basedir restriction in effect since build 467

After upgrading to the latest OctoberCMS version running under PHP 7.4 my sites where generating these Exception errors like:

An exception has been thrown during the rendering of a template ("file_exists(): open_basedir restriction in effect. File(/storage/app/media/logos/vdz-logo.png) is not within the allowed path(s):

Looking into the code I noticed that the storage path was absolute and not reading from the storage folder. By modifying the class everything works fine again. Are there more people suffering this issue? If so can you update the code?

Line 48 in Class Image.php:
$this->filePath = (file_exists(storage_path($filePath)))

Choose how to crop

Hello,

When you use the crop method for an image, the plugin always consider the focus to the center of the image.

Is it possible to add some parameters to allow to choose how to crop the image ?

If it's already possible, how could I do that ? I tried to play with the offset parameter, but it doesn't seems to do that.

Thank you

Alex

Problem to resize blog image

Hi Matthew, in my code in for > post.featured_images >
image.path = http://misite.loc/storage/app/uploads/public/5c9/...
<img src="{{ image.path | resize(350) }}" >
the error is:
Type error: Too few arguments to function ToughDeveloper\ImageResizer\Classes\Image::resize(), 3 passed in /Applications/MAMP/htdocs/ThinkDifferent/bconnected/public_html/plugins/toughdeveloper/imageresizer/Plugin.php on line 62 and exactly 4 expected

Adding all the parameters does not work either.

this don´t work too
<img src="{{ image.path | replace('http://misite.loc/','')| resize(350) }}" >

Do you have any idea how to solve it?
It's just a blog.

Watermarking?

Hi,

I'm making a site, and I would love to see a watermarking feature.
Is this some how possible?

Regards
Me

Should ignore svg

Sometimes i upload .svg images into media library, for example for logo. Using:
{{ record.logo|media|resize(false,43) }}
i get the link to non existing image - 'thumb__0_43_0_0_auto.svg'.
SVG's should be ingored when resizing, is there an option for this in settings - don't see anything in documentation

Doesn't create S3 url's

Could you point me in the right direction regarding letting this plugin work with S3 uploads? I followed OctoberCMS's instructions to get the media manager to work with S3 and that's all fine.

I now have the following in my template <img src="{{ 'image.jpg'|media|resize(200,150) }}"> but it creates a link to <domain>/storage/app/uploads/public/68a/620/f0c/thumb__200x150_0_0_crop.jpg where as <img src="{{ 'image.jpg'|media }}"> points to https://s3.eu-central-1.amazonaws.com/<bucket>/image.jpg.

It does however create the image in the S3 bucket (after adjusting the policy in AWS IAM for that user slightly) so it's just about the URL creation. Any idea on how to make this work?

Don't scale up image on resize if image is smaller then new width or height

As far as I can see, the resized image is always generated with the width and height set in the resize function, no matter what size the original image is. It would be great if an image isn't scaled up, when the original size of an image is smaller then the resized size. This way the quality of the image isn't compromised.

CI integration - Contribution wanted

I think a CI tool is essential to improve code quality and simplify PR reviews.

If anyone would like to contribute with Travis or Github Actions configs feel free to submit a PR, thankyou.

Quality settings sometimes don't work

I need to set less quality to Jpeg image for passing Google PageSpeed test.
Tried to set at plugin settings to 15 (to test it), the image quality looks is about 100 and PageSpeed failed.

This call also doesn't work:
{{ 'big_image.jpg'|media|resize(1322, 932, { quality: '15' }) }}

The only way to set better compression is to set cropping mode for the image.
{{ 'big_image.jpg'|media|resize(1322, 932, { mode: 'landscape' }) }}

So this bug definitely needs to be fixed.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.