Git Product home page Git Product logo

image's Introduction

Gregwar's Image class

Build status paypal

The Gregwar\Image class purpose is to provide a simple object-oriented images handling and caching API.

Installation

With composer :

{
    ...
    "require": {
        "gregwar/image": "2.*"
    }
}

Usage

Basic handling

Using methods chaining, you can open, transform and save a file in a single line:

<?php use Gregwar\Image\Image;

Image::open('in.png')
     ->resize(100, 100)
     ->negate()
     ->save('out.jpg');

Here are the resize methods:

  • resize($width, $height, $background): resizes the image, will preserve scale and never enlarge it (background is red in order to understand what happens):

resize()

  • scaleResize($width, $height, $background): resizes the image, will preserve scale, can enlarge it (background is red in order to understand what happens):

scaleResize()

  • forceResize($width, $height, $background): resizes the image forcing it to be exactly $width by $height

forceResize()

  • cropResize($width, $height, $background): resizes the image preserving scale (just like resize()) and croping the whitespaces:

cropResize()

  • zoomCrop($width, $height, $background, $xPos, $yPos): resize and crop the image to fit to given dimensions:

zoomCrop()

  • In zoomCrop(), You can change the position of the resized image using the $xPos (center, left or right) and $yPos (center, top or bottom):

zoomCrop() with yPos=top

The other methods available are:

  • crop($x, $y, $w, $h): crops the image to a box located on coordinates $x,y and which size is $w by $h

  • negate(): negates the image colors

  • brighness($b): applies a brightness effect to the image (from -255 to +255)

  • contrast($c): applies a contrast effect to the image (from -100 to +100)

  • grayscale(): converts the image to grayscale

  • emboss(): emboss the image

  • smooth($p): smooth the image

  • sharp(): applies a mean removal filter on the image

  • edge(): applies an edge effect on the image

  • colorize($red, $green, $blue): colorize the image (from -255 to +255 for each color)

  • sepia(): applies a sepia effect

  • merge($image, $x, $y, $width, $height): merges two images

  • fill($color, $x, $y): fills the image with the given color

  • write($font, $text, $x, $y, $size, $angle, $color, $position): writes text over image, $position can be any of 'left', 'right', or 'center'

  • rectangle($x1, $y1, $x2, $y2, $color, $filled=false): draws a rectangle

  • rotate($angle, $background = 0xffffff) : rotate the image to given angle

  • roundedRectangle($x1, $y1, $x2, $y2, $radius, $color, $filled=false): draws a rounded rectangle ($radius can be anything from 0)

  • line($x1, $y1, $x2, $y2, $color): draws a line

  • ellipse($cx, $cy, $width, $height, $color, $filled=false): draws an ellipse

  • circle($cx, $cy, $r, $color, $filled=false): draws a circle

  • fillBackground($bg=0xffffff): fills the background of a transparent image to the 'bg' color

  • fixOrientation(): return the image rotated and flipped using image exif information

  • applyExifOrientation(int $exif_rotation_value): return the image rotated and flipped using an exif rotation value

  • html($title = '', $type = 'jpg'): return the <img ... /> tag with the cache image

  • flip($flipVertical, $flipHorizontal): flips the image in the given directions. Both params are boolean and at least one must be true.

  • inline($type = 'jpg'): returns the HTML inlinable base64 string (see demo/inline.php)

You can also create image from scratch using:

<?php
    Image::create(200, 100);

Where 200 is the width and 100 the height

Saving the image

You can save the image to an explicit file using save($file, $type = 'jpg', $quality = 80):

<?php
    // ...
    $image->save('output.jpg', 'jpg', 85);

You can also get the contents of the image using get($type = 'jpg', $quality = 80), which will return the binary contents of the image

Using cache

Each operation above is not actually applied on the opened image, but added in an operations array. This operation array, the name, type and modification time of file are hashed using sha1() and the hash is used to look up for a cache file.

Once the cache directory configured, you can call the following methods:

  • jpeg($quality = 80): lookup or create a jpeg cache file on-the-fly

  • gif(): lookup or create a gif cache file on-the-fly

  • png(): lookup or create a png cache file on-the-fly

  • guess($quality = 80): guesses the type (use the same as input) and lookup or create a cache file on-the-fly

  • setPrettyName($prettyName, $prefix = true): sets a "pretty" name suffix for the file, if you want it to be more SEO-friendly. for instance, if you call it "Fancy Image", the cache will look like something/something-fancy-image.jpg. If $prefix is passed to false (default true), the pretty name won't have any hash prefix. If you want to use non-latin1 pretty names, behat/transliterator package must be installed.

For instance:

<?php use Gregwar\Image\Image;

echo Image::open('test.png')
          ->sepia()
          ->jpeg();

//Outputs: cache/images/1/8/6/9/c/86e4532dbd9c073075ef08e9751fc9bc0f4.jpg

If the original file and operations do not change, the hashed value will be the same and the cache will not be generated again.

You can use this directly in an HTML document:

<?php use Gregwar\Image\Image;

// ...
<img src="<?php echo Image::open('image.jpg')->resize(150, 150)->jpeg(); ?>" />
// ...

This is powerful since if you change the original image or any of your code the cached hash will change and the file will be regenerated.

Writing image

You can also create your own image on-the-fly using drawing functions:

<?php 
    $img_src = Image::create(300, 300)
                    ->fill(0xffaaaa)    // Filling with a light red
                    ->rectangle(0xff3333, 0, 100, 300, 200, true) // Drawing a red rectangle
                      // Writing "Hello $username !" on the picture using a custom TTF font file
                    ->write('./fonts/CaviarDreams.ttf', 'Hello '.$username.'!', 150, 150, 20, 0, 'white', 'center')
                    ->jpeg();
?>
<img src="<?= $img_src  ?>" />

Using fallback image

If the image file doesn't exist, you can configure a fallback image that will be used by the class (note that this requires the cache directory to be available).

A default "error" image which is used is in images/error.jpg, you can change it with:

<?php
    $img->setFallback('/path/to/my/fallback.jpg');

Garbage Collect

To prevent the cache from growing forever, you can use the provided GarbageCollect class as below:

<?php use Gregwar\Image\GarbageCollect;

// This could be a cron called each day @3:00AM for instance
// Removes all the files from ../cache that are more than 30 days
// old. A verbose output will explain which files are deleted
GarbageCollect::dropOldFiles(__DIR__.'/../cache', 30, true);

Development

Gregwar\Image is using PHP metaprogramming paradigms that makes it easy to enhance.

Each function that handles the image is implemented in an Adapter, this is where all the specific actions take place.

The Common adapter is design to contain common abstract actions, while the specific adapters (like GD) are designed to contain actions specific to the low level layer.

You can add your own methods by adding it in the corresponding adapter.

<?php
    // In the adapter
    private function myFilter()
    {
        $this->negate();
        $this->sepia();
    }

Which could be used on the Image

<?php
    $image->myFilter();

You can also write your own adapter which could extend one of this repository and use it by calling setAdapter():

<?php
    $image->setAdapter(new MyCustomAdapter);

License

Gregwar\Image is under MIT License, please read the LICENSE file for further details. Do not hesitate to fork this repository and customize it !

image's People

Contributors

10257 avatar abhimanyu003 avatar barryvdh avatar born2discover avatar coolgoose avatar cord avatar david-fanin avatar flaviocopes avatar garygreen avatar glensc avatar gormur avatar gregwar avatar jfoucher avatar knifesk avatar oojacoboo avatar ozahorulia avatar robbanl avatar rotzbua avatar soullivaneuh avatar soundslocke avatar takeno avatar turbohz avatar wodka avatar yamilovs avatar yemyat 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  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

image's Issues

Separate Composer Package

I would be great to have this awesome class as separate Composer package for projects that don't use Symfony 2 and Twig.

->jpeg()

the jpeg method returns the cache path, as stated in the docs.. is there any way to get the jpeg data out of the box?

i.e.

header('Content-Type: image/jpeg'); //sets the header.. maybe this could be pushed by the lib itself
echo $image->jpegData();  //outputs the raw jpg data

Question

Hello, bundle has compatible with url image please ?

Example:

...

Image::open('http://www.site.com/img.png')
->resize(100, 100)
->negate()
->save('out.jpg');

...

Thanks :)

Probleme with save method always return false

Probleme with save method always return false Ligne 510, Image.php

return use by cacheFile line 396, result method cacheFile return false when first

generate cache image file
if (!$success) {
return false;
}

Result problem do not return image when first view.

P.S : I Speak french, sorry for my english

Error during generate non-existing file

This is part of my template.

{{ image('image_uploads/' ~ program.id ~ '.jpg').resize(118,88) }}

When file don't exist occurs error.

<img src="/
Fatal error: Method Gregwar\ImageBundle\ImageHandler::__toString() must not throw an exception in /home/pchludzinski/www/d3/Symfony/app/cache/dev/classes.php on line 7063

[PHP7] Undefined constant 'IMG_JPG'

When I try to run my application on php7, I got this error on runtime image rendering:

Fatal error: Undefined constant 'IMG_JPG'
500 Internal Server Error - FatalThrowableError

1. in vendor/gregwar/image/Gregwar/Image/Image.php at line 285
2. at Image ->setAdapter ('gd') 
in vendor/gregwar/image/Gregwar/Image/Image.php at line 269
...

Fill transparent image with white background

If I use this

<img src="<?php echo Image::open('tux.png')->jpeg(); ?>" />

png image is filled with black background.

Example

From this

tux


To this

1849d6a880ed1632bd6e2b2700c5dc75e13


But if i use this code

<img src="<?php echo Image::open('tux.png')->zoomCrop(400, 479)->jpeg(); ?>" >

Every thing works fine the image is filled with white background not black.

What i have to do to fill image with white background not black while converting it form png to jpg

Resize function

Dear Gregwar,

There is a problem with your _resize function. The function does not conserve the alpha channel of an image. Transparency pixels are turns into white pixels after the resizing.

Best regards.

Leph

Default type for save should always be original

Right now the default type for a save is "jpeg" which in the case of certain images might not be desired.

The library should use the value it gets from guessType() during __construct() as a default when saving the image.

Upload and Save image

I tried to upload image and save it. It works perfectly with JPG format but when try to upload other format like png, gif it gives UnexpectedValueException error

I have created a short video to show you what exactly I mean

Video link:- http://d.pr/v/Agc0

It would be great we can upload and save image files like this ( as shown in video ) as it will give us flexibility to re-size images before saving them in directory.

rectangble methods do not work

Hi, both rectangle methods give me an exception:
Error: Exception: Not enough arguments given for roundedRectangle (in /www/beta/site/modules/PageGIM/lib/Gregwar/Image.php line 355)
#0 [internal function]: Gregwar\Image\Image->__call('roundedRectangl...', Array)
#1 [internal function]: Gregwar\Image\Image->roundedRectangle(Array)
#2 /www/beta/site/modules/PageGIM/lib/GimBridge/GimBridge.class.php(31): call_user_func(Array, Array)
#3 /www/beta/site/templates/tpl_profile.php(101): GimBridge->__call('roundedRectangl...', Array)
#4 /www/beta/site/templates/tpl_profile.php(101): GimBridge->roundedRectangle(10, 10, 370, 50, 2, '#000000', true)
#5 /www/beta/wire/core/TemplateFile.php(169): require('/www/beta/site/...')
#6 [internal function]: TemplateFile->___render()
#7 /www/beta/wire/core/Wire.php(389): call_user_func_array(Array, Array)
#8 /www/beta/wire/core/Wire.php(344): Wire->runHooks('render', Array)
#9 /www/beta/wire/modules/PageRender.module(356): Wire->__call('render', Array)
#10 /www/beta/wire/modules/PageRender.module(356): TemplateFile->render()
#11 [inter

This error message was shown because you are logged in as a Superuser. Error has been logged.

I call it like this:
$imgnew = $imgold->gimLoad('prefix')->roundedRectangle(10,10,370,50,2,"#000000",TRUE)->gimSave();

No idea what is wrong

Définir le dossier cache

Bonjour, je ne trouve pas où l'on peut définir le dossier cache, des infos la dessus svp ? :)
Merci.

Image object from resource

Is there any way that I can create Image object from already existed image resource not from file e.g. if I load image from database (in this case I must first save that image in file on disk and than create Image object using that file. When I finish processing image I will save new image in database and delete old file. Saving loaded image from database on dis is not necessary).

[New feature] ZoomCrop expansion

It would be aweome if we could use the zoomCrop() method that takes an extra argument.

quadrant($quadrant) - Crop the remaining overflow of an image using the passed quadrant heading. The supported $quadrant values are: T - Top (good for headshots), B - Bottom, L - Left, R - Right, C - Center (default, that's the case right now).

What do you think of this new feature?

resize image i Sonata

Hello!

How to use this functionality in ImageAdmin.php for example

I use Sonata with Admin Controllers...

Add method to get path to image.

If I end up passing an instance of your Image class to another method, I have no way of getting the filename from your class. I effectively have to pass the filename along with the instance.

Would be nice if I could go $image->getFilePath()

Constants from the global namespace not imported.

In Gregwar\Image\Image.php, GD image constants are being referenced without being imported into the current namespace.

You can fix this by either importing them at the top of the file or tossing a backslash in front of them. Right now this is preventing your library from working :(

black background while resizing gif

Hello,
magot

I have a gif with a transparent background.
While re-sizing it with your tool, it applied a black background on it.

I don't get that for png files.

Any idea what could be the cause ?
Best regards,
Pierre

Install without Composer?

I don't have SSH access at my shared hosting. Is it possible to install Gregwar/Image without using Composer?

getting background color

would it be possible to include something like a background guesser which retrieves the most used pixel color. Or retrieve the color of the first non-transparent pixel in the top most left corner? That would be great to fill images with a background color.

Extendable Image class

I've tried to extend the \Gregwar\Image\Image class. I've included it with Composer.
But the Image::open method doesn't use late static binding, I cannot overwrite the cacheDir property.

This is the original method
/**
* Creates an instance, usefull for one-line chaining
*/
public static function open($file = '')
{
return new self($file);
}

If you used late static bindig, it would become extendable

/**                                                                                                                                                           
 * Creates an instance, usefull for one-line chaining                                                                                                         
 */                                                                                                                                                           
public static function open($file = '')                                                                                                                       
{                                                                                                                                                             
    return new static($file);                                                                                                                                 
}

Resizing/zoomCrop not working with GIF

Resizing/zoomCrop is not working with GIF image
Image::open('in.gif')->resize(100, 100)->guess()
the format output is still GIF but image looses it's animation property

Utilisation dans un Cron

Bonjour,

j'ai un petit souci concernant l'utilisation du bundle par l'intermédiaire d'un cron.

j'utilise dans ma méthode ceci 👍

$this->getContainer()->get('image.handling')->open($performerPicture->picture->URL)->zoomCrop(133,97)->save(basename($performerPicture->picture->URL),'jpg',100);

mon image dans $performerPicture->picture->URL est du genre http://monsite.fr/images/image.jpg

Je n'ai aucune erreur au passage de ce script, cependant l'ensemble de mes images se créer dans le repertoire ou ce trouve la console..

J'aimerais qu'un hash soit générer afin que je puisse directement appeler mon image en cache dans mes vues

Est ce que j'ai oublié un truc ?

Merci d'avance pour votre aide

Decad7

Sharp

sharp() method is barely useful - it adds too much of sharp, probably there is a possibility to add as a param amount of sharp wanted

Resizing fallback images

Hey,

Would it be possible to have the fallback image get resized to the dimensions requested for the original image?

Currently we have a fairly large placeholder image and request images in many different sizes.

Thanks!

Keep Metadata information (EXIF, IPTC)

Hi,

First your library is awesome and very usefull.

But when I use the resize function, the image lose his metatdata information.

I know that the most people don't need them. But in my case I must keep this informations.

It is possible to add this kind of feature in your library?

By advance, thanks.

Can't create transparent image

Is it possible to create a transparent image ?
This code create a white gif :

Image::create($width, $height)
            ->fill('transparent')
            ->cacheFile('gif');

Write an Imagick adapter

If someone is motivated, I think we could easily write an Imagick adapter to handle image using the Imagick PHP library

(see #32)

Function guess() not working

I'm having an issue with the function guess()
The saved image is always a .jpeg.

From the demo cache.php :

echo Image::open('img/test.png')->sepia()->guess();
result in: cache/images/1/2/3/7/f/1bdb743fb85b8445cf12a0a58a25e3edaa0.jpeg

I found a solution with the following work around :

$img = Image::open('img/test.png');
$type = $img->guessType();
$img->sepia()->cacheFile($type);

More possibilities to get information about the current image

Hey there,

since your class does not support dimension calculation for all resizing methods (e.g. cropZoom) I wanted to suggest that you implement some methods to get information about the current image. I am talking about height, width and so on.
So it would be easier to calculate the dimensions outside the class without the need of another ressource or that getimagesize() non-sense.

Regards
func0der

Bug: resize() enlarges images without keeping original ratio. Fix provided.

Hi there!
I found a (possible) bug using the image-bundle:

The Readme tells that resize() should not enlarge images, preserving original ratio.
If I ask the library to resize a 350x50 image specifying only one dimension, eg.

->resize(500, 0)

I expect the library not to rescale it.
The library, instead, outputs a 500x50 image, with padded pixels at both sides.

This is not a correct behaviour, I think.

I may have found the issue and fixed it.

In Adapter/Common.js, lines 190:196

        if ($width == null || $crop) {
            $width = $new_width;
        }

        if ($height == null || $crop) {
            $height = $new_height;
        }

should become:

        if ($width == null || $crop || $scale == 1) {
            $width = $new_width;
        }

        if ($height == null || $crop || $scale == 1) {
            $height = $new_height;
        }

to prevent raw target values being passed to doResize() function.

Thank you!

Black background on PNG file

We are having an issue where our image is displaying a black background when creating it.

echo Image::fromData($file)
                ->write($this->font_file, $text, $left, $top, $font_size, 0, 'black', 'center')
                ->get('png');

We tried correcting this with the ->fillBackground(0xffffff) method, but that just makes the background white after testing the image live and changing the body of the HTML to something other than white.

echo Image::fromData($file)
                ->write($this->font_file, $text, $left, $top, $font_size, 0, 'black', 'center')
                ->fillBackground(0xffffff)
                ->get('png');

Set Cache Dir

Hi, I was wondering if its possible to set the cache dir on the fly, without creating an instance. Actually, I don't know how to create a cache dir to activate it.

Resize image but never enlarge it

I Re-size a 200 x 200 px image using this code

Image::open('test.jpg')->resize(400,400)->save('new.jpg');

according to resize() it must not get enlarged.
But what is happening it add extra white background to image and resize it 400 x 400 px. Ok image is not resided but it's just a wider canvas now

Example:-
Resizing 200x 200px image

test


Extra white space is added

new


It would be great if there is a method to not to enlarge image, just leave it to it's original pixel if re-size is greater than image's original pixel

Write a Gmagick adpater

As same as #34, Gmagick is an another official extension of PHP for image manipulation.

Could be great to implement it. Will probably work on it after #65 if I have enough time.

Petit problème

Bonjour, j'ai un petit problème:

J'utilise la class Image dans mon entité pour mon bundle ImageBundle et du coup ça entre en conflit avec votre bundle :

Fatal error: Cannot use Kyna\ImageBundle\Entity\Image as Image because the name is already in use in C:\wamp\www\Project_V1\Symfony\src\Kyna\ImageBundle\Controller\ImageController.php on line 9

Dans mon controller :

use Gregwar\Image;
use Kyna\ImageBundle\Entity\Image;

J'utilise 4 bundle que je dévellope: ImageBundle, VideoBundle, FileBundle, ModBundle et ce genre de problème ne ce produit qu'avec le votre, le nom est un peu trop commun pour un bundle destiné à être intégré dans ton type de site, j'ai déjà des relations dans tous les sens de même pour mes controller et tout changer sans créer des erreurs dans tous les sens est quasiment impensable.

Serait il possible de donner un nom moins commun à vos class pour éviter ce problème svp ? :)
Merci.

Trouble getting cache working...

I'm creating an image like so and the $file is a stream of the PNG's data, I tried creating a cache dir where the Image class was with 777 perms and still nothing. Also tried using the ->png() method instead of ->get().

echo Image::fromData($file)
                ->write($this->font_file, $text, $left, $top, $font_size, 0, 'black', 'center')
                ->get('png');

Custom filter

I would like to create a custom filter so I have this:

abstract class Adapter implements AdapterInterface
{
//....
    private function myFilter()
    {
        die("Entering in my myFilter");
        $this->negate();
        $this->sepia();
    }
}

I have this code in my view:

src="{{ image('images/' ~ producto.imageName).myFilter

but Entering in myFilter is never shown..

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.