Coder Social home page Coder Social logo

imagecow's Introduction

Imagecow

Build Status Scrutinizer Code Quality

Created by Oscar Otero http://oscarotero.com [email protected]

What is Imagecow?

It's a php library to manipulate images to web.

  • PHP >= 5.5
  • Use GD2 or Imagick libraries
  • Very simple, fast and easy to use. There is not a lot of features, just the basics: crop, resize, resizeCrop, etc.

Simple usage example:

use Imagecow\Image;

Image::fromFile('my-image.gif')
    ->autoRotate()
    ->resizeCrop(300, 400, 'center', 'middle')
    ->format('png')
    ->save('converted-image.png')
    ->show();

How use it?

Installation

This package is installable and autoloadable via Composer as imagecow/imagecow.

$ composer require imagecow/imagecow

Creating a Imagecow\Image instance:

use Imagecow\Image;

//Using Imagick:
$image = Image::fromFile('my-image.jpg', Image::LIB_IMAGICK);

//Detect the available library automatically
//(in order of preference: Imagick, Gd)
$image = Image::fromFile('my-image.jpg');

//Create an instance from a string
$image = Image::fromString(file_get_contents('my-image.jpg'));

resize

Image::resize($width, $height = 0, $cover = false)

Resizes the image keeping the aspect ratio.

Note: If the new image is bigger than the original, the image wont be resized

  • $width: The new max-width of the image. You can use percentages or numbers (pixels). If it's 0, it will be calculated automatically using the height
  • $height: The new max-height of the image. As width, you can use percentages or numbers and it will be calculated automatically if it's 0
  • $cover: If it's true, the new dimensions will cover both width and height values. It's like css's image-size: cover.
//Assuming the original image is 1000x500

$image->resize(200);                    // change to 200x100
$image->resize(0, 200);                 // change to 400x200
$image->resize(200, 300);               // change to 200x100
$image->resize(2000, 2000);             // keeps 1000x500

crop

Image::crop($width, $height, $x = 'center', $y = 'middle')

Crops the image:

  • $width: The width of the cropped image. It can be number (pixels) or percentage
  • $height: The height of the cropped image. It can be number (pixels) or percentage
  • $x: The horizontal offset of the crop. It can be a number (for pixels) or percentage. You can also use the keywords left, center and right. If it's not defined, used the value by default (center).
  • $y: The vertical offset of the crop. As with $x, it can be a number or percentage. You can also use the keywords top, middle and bottom. If it's not defined, used the value by default (middle).
$image->crop(200, 300);                 // crops to 200x300px
$image->crop(200, 300, 'left', 'top');  // crops to 200x300px from left and top
$image->crop(200, 300, 20, '50%');      // crops to 200x300px from 20px left and 50% top
$image->crop('50%', '50%');             // crops to half size

Automatic cropping

Imagecow includes some code copied from the great library stojg/crop to calculate the most important parts of the image to crop and resizeCrop automatically. The available methods are:

Note: these methods are available only for Imagick. If you use Gd, the methods fallback to "center", "middle" positions.

To use them:

$image->crop(500, 200, Image::CROP_ENTROPY);  // crops to 500x200 using the Entropy method to calculate the center point
$image->crop(500, 200, Image::CROP_BALANCED); // The same as above but using the Balanced method

resizeCrop

Image::resizeCrop($width, $height, $x = 'center', $y = 'middle')

Resizes and crops the image. See resize and crop for the arguments description.

$image->resizeCrop(200, 300);                  //Resizes and crops to 200x300px.
$image->resizeCrop('50%', 300);                //Resizes and crops to half width and 300px height
$image->resizeCrop(200, 300, 'left', '100%'); //Resizes and crops to 200x300px from left and bottom
$image->resizeCrop(200, 300, Image::CROP_BALANCED); //Resizes and crops to 200x300px using the CROP_BALANCED method

rotate

Image::rotate($angle)

Rotates the image

  • $angle: Rotation angle in degrees (anticlockwise)
$image->rotate(90); // rotates the image 90 degrees

autoRotate

Image::autoRotate()

Autorotates the image according its EXIF data

$image->autoRotate();

opacity

Image::opacity($value)

Set the alpha channel of the image. The value must be between 0 (transparent) to 100 (opaque). Note that the image will be converted to png (if it's not already)

$image->opacity(50);

blur

Image::blur($loops = 4)

Applies the gaussian blur to the image. The more loops, the more the image blurs.

$image->blur(8);

watermark

Image::watermark($image, $x = 'right', $y = 'bottom')

Applies a image as a watermark. You can configure the position and opacity.

$image = Image::fromFile('photo.jpg');
$logo = Image::fromFile('logo.png');

$logo->opacity(50);

$image->watermark($logo);

format

Image::format($format)

Converts the image to other format.

  • $format: The format name. It can be "jpg", "png", "gif", or "webp"*.
$image->format('png'); // converts to png

*Note: webp format is only supported when using Imagick. ImageMagick must be built with WEBP support.

save

Save the image to a file.

  • $filename: The filename for the saved image. If it's not defined, overwrite the file (only if has been loaded from a file).
$image->save('my-new-image.png'); // save to this file
$image->save(); // overwrite file

setBackground

Image::setBackground(array $background)

Set a default background used in some transformations: for example on convert a transparent png to jpg.

  • $background: An array with the RGB value of the color
$image->setBackground(array(255, 255, 255)); // set the background to white

quality

Image::quality($quality)

Defines the image compression quality for jpg images

  • $quality: An integer value between 0 and 100
$image->quality(80); // change the quality to 80

setClientHints

Image::setClientHints(array $clientHints)

Defines the client hints to fix the final size of the image and generate responsive images. The available client hints are:

  • dpr Device pixel ratio
  • width The final image width
  • viewport-width The viewport width
$image->setClientHints([
    'dpr' => 2,
    'width' => 300,
    'viewport-width' => 1024,
]);

More information about client hints below.

Display the image

Send the HTTP header with the content-type, output the image data and die:

$image->show(); // you should see this image in your browser

Insert the image as base64 url:

echo '<img src="' . $image->base64() . '">';

Get image info:

There are other functions to returns image info:

  • $image->getWidth(): Returns the image width in pixels
  • $image->getHeight(): Returns the image height in pixels
  • $image->getMimeType(): Returns the image mime-type
  • $image->getExifData(): Returns the EXIF data of the image
  • $image->getString(): Returns a string with the image content

Execute multiple functions

You can execute some of these functions defined as a string. This is useful to get images transformed dinamically using variables, for example: image.php?transform=resize,200,300|format,png. All operations are separated by | and use commas for the arguments:

$image->transform('resize,200,50%|format,png|crop,100,100,CROP_ENTROPY');

//This is the same than:
$image
	->resize(200, '50%')
	->format('png')
	->crop(100, 100, Image::CROP_ENTROPY);

Responsive images

Imagecow has support for client hints, that allows to generate responsive images without using cookies or javascript code (like in 1.x version of imagecow). Client Hints is introduced by Google becoming a standard. Here's a deep explain of how to use it

Note that currently this is supported only by chrome and opera browsers.

Simple example:

In your webpage, add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>My webpage</title>
    <!-- Activate client hints -->
    <meta http-equiv="Accept-CH" content="DPR,Width,Viewport-Width"> 
</head>
<body>
    <!-- Insert a responsive image -->
    <img src="image.php?file=flower.jpg&amp;transform=resize,1000" sizes="25vw">
</body>
</html>

Now, in the server side:

use Imagecow\Image;

$file = __DIR__.'/'.$_GET['file'];
$transform = isset($_GET['transform']) ? $_GET['transform'] : null;

//Create the image instance
$image = Image::fromFile($file);

//Set the client hints
$image->setClientHints([
    'dpr' => isset($_SERVER['HTTP_DPR']) ? $_SERVER['HTTP_DPR'] : null,
    'width' => isset($_SERVER['HTTP_WIDTH']) ? $_SERVER['HTTP_WIDTH'] : null,
    'viewport-width' => isset($_SERVER['HTTP_VIEWPORT_WIDTH']) ? $_SERVER['HTTP_VIEWPORT_WIDTH'] : null,
]);

//Transform the image and display the result:
$image->transform($transform)->show();

Other utils

IconExtractor.

Only for Imagick. Class to extract the images from an .ico file and convert to png.

use Imagecow\Utils\IconExtractor;

$icon = new IconExtractor('favicon.ico');

//Gets the better image from the icon (quality = color_depth + (width * height))
$image = $icon->getBetterQuality();

//Do imagecow stuff
$image->resize(100)->save('my-image.png');

SvgExtractor.

Only for Imagick This class allows generate images from a svg file (useful for browsers that don't support svg format):

use Imagecow\Utils\SvgExtractor;

$svg = new SvgExtractor('image.svg');

//Gets the image
$image = $svg->get();

//Now you can execute the imagecow methods:
$image->resize(200)->format('jpg')->save('image.jpg');

Installing ImageMagick with WEBP support

macOS

Via Homebrew:

brew install webp
brew install imagemagick --with-webp

CentOS/RHEL

yum install libwebp-devel rpm-build
mkdir /tmp/imagemagick
cd /tmp/imagemagick
yum-builddep ImageMagick -y
yumdownloader --source ImageMagick
rpm -ivh ImageMagick*
sed -i '/BuildRequires:\tghostscript-devel/a BuildRequires:\tlibwebp-devel' /root/rpmbuild/SPECS/ImageMagick.spec
sed -i '/Requires: pkgconfig/a Requires: libwebp' /root/rpmbuild/SPECS/ImageMagick.spec
rpmbuild -ba /root/rpmbuild/SPECS/ImageMagick.spec
rpm -Uvh --force /root/rpmbuild/RPMS/x86_64/ImageMagick-*.rpm
yum-config-manager --save --setopt=updates.exclude=ImageMagick*;

Ubuntu

mkdir /tmp/imagemagick
cd /tmp/imagemagick
apt-get build-dep imagemagick
apt-get install libwebp-dev devscripts
apt-get source imagemagick
cd imagemagick-*
debuild -uc -us
dpkg -i ../*magick*.deb

Maintainers:

  • @oscarotero (creator)
  • @eusonlito (collaborator)
  • and more...

Thanks to

Stig Lindqvist and Julien Deniau jdeniau for the stojg/crop library

imagecow's People

Contributors

aemr3 avatar endelwar avatar eusonlito avatar hrach avatar kevbaldwyn avatar kuczmaja avatar nysos3 avatar oscarotero avatar peter279k avatar scrutinizer-auto-fixer 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

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

imagecow's Issues

Svg to jpg/png error

no decode delegate for this image format `' @ error/blob.c/BlobToImage/361 in
/SvgExtractor.php:69\nStack trace:\n#0 s
src/Utils/SvgExtractor.php(69): Imagick->readimageblob()\n#1
/new.php(10): Imagecow\Utils\SvgExtractor->get()\n#2 {main}\n thrown in
/src/Utils/SvgExtractor.php on line 69

Add quality as transform parameter?

I have some images in a project that need to have more quality than others.

There are any way to pass the quality parameter from transform options?

I'm using a stylecow wrapper and is the easiest way to customize some thumbnails from template without need a coder (like sizes).

Thanks!

Potential composer problem

I'm using this package https://github.com/kevbaldwyn/image/ in an app I'm building. This package leverages yours. However when installing the package composer throws errors concerning your package.

You can find a discussion about this here: kevbaldwyn/image#10

The package maintainer believes the problem lies with your setup. Could you please join this discussion, so we can resolve any problem any potential problems on your end?

Thanks for your great work

Create the output directory before calling save()

I had the issue that Imagick crashed if the folder I want to save the image in does not yet exist. Couldn't this library implement such a feature before saving images, first to ensure it works as one could except by default and avoid repetition in user-land implementations ?

Imagick add support format detection

imagecow/src/Libs/Imagick.php

example:

  public static function checkCompatibility()
    {
        return extension_loaded('imagick')  && (count(BaseImagick::queryformats()) > 0);
    }

The crop method '0' is not available for Imagick

Hi,
I'm getting The crop method '0' is not available for Imagick error when I pass 0 (int value zero) as third param of crop method like this:

$imageStandard = Image::fromFile($imgSource . '/' . $filename)
                            ->autoRotate()
                            ->crop($cropData['width'], $cropData['height'], $cropData['offsetX'], $cropData['offsetY'])
                            ->resize($this->imageWidth, $this->imageHeight)
                            ->save($imgDestination . '/' . $filename);

$cropData is an array with int values (['width' => 725, 'height' => 458, 'offsetX' => 0, 'offsetY' => 15])

On row 328 of Image.php switch statement is entered in any case and getCropOffsets method is run in any case (see this example on 3v4l https://3v4l.org/6eitl), even if $x is an integer.

A quick hack that "works for me"โ„ข is wrapping switch statement in an if (is_string($x)) {}

The background color of rotated image

The image background color will be the black after rotating the image.
Both GD2 and Imagick have this same issue.
The GD2 seems that it only happens on the GIF image format and the Imagick happens on the all image formats.

The GD2 rotates GIF image issue is similar with that repository issue. I also fix them.

And I'm not sure how to fix the Imagick problem.

Thanks.

Divide by zero when using BALANCED

When x is set to BALANCED in the crop() function, given the image is square, will result in a divide by zero exception on line 93 of file Balanced.php.

Quality for jpges not changing

Hi, i have this code:
$quality = 80; $image = Image::fromFile($file); $image->autoRotate(); if(!empty($wm)){ $watermark = Image::fromFile($wm); $image->watermark($watermark, $x = 'right', $y = 'bottom'); } $image->quality($quality); $image->resize($w, $h); $image->save($dest);

I can set quality 10 or 90 the image size (in kb) and quality afters save is the same :(

(Imagick) Suggestion to allow setting filter type and blur for better resize quality.

Hi,

Just a suggestion for the Imagick implementation in imagecow. Specifically, in Libs/Imagick.php, on line 229 where it uses scaleImage():

if ($this->image->scaleImage($width, $height) !== true) {
https://www.php.net/manual/en/imagick.scaleimage.php

ScaleImage() does not allow configuration of the filter or blur setting. The function resizeImage() is very similar but allows for changing these settings.
https://www.php.net/manual/en/imagick.resizeimage.php

For example we set the filter to Lanczos, and blur to 0.8:
if ($this->image->resizeImage($width, $height, \Imagick::FILTER_LANCZOS, 0.8) !== true) {

This vastly improved the quality of resized images. Especially ones with text on them.

Progressive image

Hello,

Does imagecow provide imageinterlace method?

If not it could be nice (and very easy to had)

PHPStorm doesn't see Imagecow namespace

Hi Oscar,

PHPStorm doesn't recognize use Imagecow\Image as valid. I've looked in vendor/composer/autoload-real.php for clues, and it looks the same as all my other dependencies (v2.3.2)

Any idea what might be different about your PSR-4 setup that would cause this?

Providing a binary or a way to get back the command for improved performances

For a project of mine where I needed great performance, I created a minimalist Symfony Console application that executes a "balanced crop", taking the input and output images paths and the width and height as arguments (see here).

However, in terms of performances, it's far from perfect compared to using Imagick's convert binary directly. Would there be a way to achieve a balanced crop using convert and this library together (something like generating the arguments I need to provide to convert from the library and then executing the command via exec) ?

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.