claviska / simpleimage Goto Github PK
View Code? Open in Web Editor NEWA PHP class that makes working with images and GD as simple as possible.
License: MIT License
A PHP class that makes working with images and GD as simple as possible.
License: MIT License
hi, i'm succesfully installed the library and i'm able to apply changes to images but i need to save the new image on another file. this is my code:
rotate(90); $img->save('img/b.png'); ?>followed the instruction here on github but this script overwrites a.jpg instead of creating b.png
am i doing something wrong? how can i solve this?
Hello i want to make the overlay layer to fit with resized image.
It is possible?
Example
$img->resize(320, 200);
$img->overlay('watermark.png', 'center center', .5, -10, -10, [width,height,auto,none]);
-The width and height resize the overlay layer to this values
-The auto resize the overlay with the same values with image
-The none keep the values from overlay source.
Hi You,
I have a image (400 * 800 or any size) . How to resize to 800 * 800 ?
width = 400px;
height = 800px;
New image have background = white and old image is center and width = width + 400px;
Thanks so much.
Hi,
I like the class! But it works strangely in some cases for me.
If I rotate to something other than 90, 180, or 270, the generated (need) background is back, not transparent. Is there a way to make it transparent?
It happens also with some other methods that have to add some background.
PhpDoc comments makes easier to work with class and it's methods, than current variant, which is not recognized by IDE.
I'm looking for a way to automate making splashscreens for my apps. For each app I need to create 7 to 9 different sizes so I'm hoping to do the following:
Input a logo (square), resize it to the width of the splashscreen, combine it with a canvas which has the width and height of the splashscreen and filled with the color of the upper/left pixel of the logo. Example:
The logo must be resized to 768x768px, the background canvas must be 768x1004px, the logo will be "pasted" on top of the background canvas.
Can this be done?
I have tried "adaptive_resize" and this almost does the job, but when creating smaller screens (320x640px) part of the logo is cut off. Seeing SimpleImage can also create images ($img = new abeautifulsite\SimpleImage(null, 200, 100, '#000');) I guess I only need to combine the 2 images.
When saving gifs it gives an "unsupported error" and "result not defined" error on line 888. Here's a suggested fix:
// before switch statement, initialize result
$result = FALSE;
// define gif image function in the switch statement
case 'gif':
$result = imagegif($this->image, $filename);
break;
When using this code:
$img->load($src_dir."150x180/".$row[$db_afb])->resize(175, 210)->save($des_dri."175x210/".$new_image);
I'm getting a notice.
Notice: Undefined variable: imagestring in C:\xampp\htdocs\lib\classes\abeautifulsite\SimpleImage.php on line 1096
This is really a great project. Thank you for your hard work. It proves to be a very good library for working with images.
It would be nice to have the PHP Basic Coding Standard (PSR-1) adopted. Is there a road map for this implementation?
Hi, great class, but i have a quest...
I need, to a gallery thumb resize on-fly without save images... just for not overload the server, this is posible with your excelent script?
thanks so much
I'm using this piece of code:
$img = new SimpleImage($src);
// Resize image;
$img->best_fit($width, $height);
// Save image and output resized image.
$img->save($folder . '/' . $src)->output();
But all time it's log:
PHP Warning: imagedestroy(): 6 is not a valid Image resource in /home/ubuntu/sites/www.noticiasagricolas.com.br/includes/SimpleImage.php on line 57
For now, using is_resource inside of if statement of __destruct function solve the problem, but I think that this is not the best solution.
Parse error: syntax error, unexpected ':' in line no SimpleImage.php on line 252
Maybe its just me but I find it to be very frustrating that I cant save newly created image to another dir;
$img->save("article-pics/thumb-".$slika);
Unable to save image: article-pics/thumb-3.jpg
Is there any way to $img->move("where/the/heck/i/want") ? :)
Hi,
Testcase:
$img = new abeautifulsite\SimpleImage("/var/www/htdocs/img/logos/test.gif");
$img->best_fit("100", "100");
$img->output();
-> Black background.
Unfortunately I didn't use github yet so I don't know how to provide the fix other then in this Ticket.
I used the code from https://github.com/maxim/smart_resize_image
I replaced the function SimpleImage->resize:
function resize ($width, $height) {
$new = imagecreatetruecolor($width, $height);
if (($this->original_info["format"] == "gif") || ($this->original_info["format"] == "png")) {
$trnprt_indx = imagecolortransparent($this->image);
// If we have a specific transparent color
if ($trnprt_indx >= 0) {
// Get the original image's transparent color's RGB values
$trnprt_color = imagecolorsforindex($this->image, $trnprt_indx);
// Allocate the same color in the new image resource
$trnprt_indx = imagecolorallocate($new, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
// Completely fill the background of the new image with allocated color.
imagefill($new, 0, 0, $trnprt_indx);
// Set the background color for new image to transparent
imagecolortransparent($new, $trnprt_indx);
} elseif ($this->original_info["format"] == "png") {
// Always make a transparent background color for PNGs that don't have one allocated already
// Turn off transparency blending (temporarily)
imagealphablending($new, false);
// Create a new transparent color for image
$color = imagecolorallocatealpha($new, 0, 0, 0, 127);
// Completely fill the background of the new image with allocated color.
imagefill($new, 0, 0, $color);
// Restore transparency blending
imagesavealpha($new, true);
}
}
imagecopyresampled($new, $this->image, 0, 0, 0, 0, $width, $height, $this->width, $this->height);
$this->width = $width;
$this->height = $height;
$this->image = $new;
return $this;
}
It's still his code style and all comments included. So please could someone use this to update SimpleImage?
Works fine for me, except in one test image I had there was:
a) transparent colour
b) red colour
c) white colour
After resizing, I still had transparent and red colour not no more white colour. this was also transparent.
PS: I'm running PHP 5.3.22; GD bundled (2.0.34 compatible)
Thank you well!
Daniel
Hi,
I've change the quality to 0-100 (as a percent)
https://gist.github.com/4196750
I think it's better to use no?
When i want to scale a realy big image (5,7mb / 4128px x 3096px) to 800+/- x 600+/-, it create a black background only. I think the image is so large that the time to create a resize is to short.
It seems you've update your lib recently, but the version still says 2.3 as was the very old one.
I would love to see bit depth added into SimpleImage, I just had a large dimension PNG8 original, but now I'm seeing that after being resized to 1/9 of the dimension area that it's about 3x the original file size : (
I found this stackoverflow that may help
http://stackoverflow.com/questions/5752514/how-to-convert-png-to-8-bit-png-using-php-gd-library
but as you see it's horrible quality, although someone mentioned another method, but relies on an external program that uses an algorithm : , but that might work for simple graphics?
I'm going to keep looking around to see if anyone has the algorithms fully in PHP.
I work with animated GIF, after save() the new image is not animated.
Any solution for this?
Working with an image size of 229 x 96.
When I proportionally resize the image to 105px width, the height we get is 44px. But I need a 77px height, so I then crop it to 77px height (larger height than available area) which leaves everything beyond 44px black. Any way to make that area transparent too?
Here's the methods I'm applying:
$image->fit_to_width(105)->crop(0, 0, $image->get_width(), 77)->save(IMG_DIR);
Found while using my own solution, and then solved once we moved to your class structure because it became easier to track down. in any case that you are using the file format should add the cases '8', '16', and '32' to the same lock of code as used for 'png'.
The issue arises in certain saving scenarios (best replication method - use mac OS's screengrabber functionality to create an image. the file format of this png will be 32, NOT png.
Hello,
When I resize a PNG with a transparent background, then I save it on JPG, the backgorund is black.
How I can make a white background ?
Thanks
Really like you class but for some reason when rotating an image the background color changes from white to #FCFEFC. The code i am using is:
$img = new abeautifulsite\SimpleImage('label.gif');
$img->rotate(90, array(255,255,255))->save('thumb.gif', 100);
Nothing fancy just rotating an white label with a barcode on it. Buf after rotated the thumb.gif has a the mentioned background color.
Erwin
I'm probably posting this in the wrong place; my apologies if so.
I've added $left and $top parameters to thumbnail() that allow for custom positioning of thumbnails. For the purposes of the software I work on, I set the parameters both to 0 (captures top of image and crops vertical overflow below the width of the thumbnail). Here's my new version of thumbnail():
function thumbnail($width, $height = null, $left=null, $top=null) {
// Determine height
$height = $height ?: $width;
// Determine aspect ratios
$current_aspect_ratio = $this->height / $this->width;
$new_aspect_ratio = $height / $width;
// Fit to height/width
if ($new_aspect_ratio > $current_aspect_ratio) {
$this->fit_to_height($height);
} else {
$this->fit_to_width($width);
}
if(is_null($left)){
$left = floor(($this->width / 2) - ($width / 2));
}
if(is_null($top)){
$top = floor(($this->height / 2) - ($height / 2));
}
// Return trimmed image
return $this->crop($left, $top, $width + $left, $height + $top);
}
Not sure if others would find this useful, but I wanted to pass it along regardless. In any case, thanks for your work on SimpleImage; it makes my life much, much easier on a regular basis.
Using the output() method results in an error
PHP Warning: imagedestroy(): is not a valid Image resource in SimpleImage.class.php on line 24
This is because the output() method calls the class destructor on line 757.
This is wrong, because the destructor is always running at the end automatically.
So when calling the destructor manually like you do in the output() method the destructor runs twice, resulting the error, because the second time the image resource is already destroyed.
Test image: http://i.imgur.com/4b8leWA.gif
$img = new \abeautifulsite\SimpleImage('test.gif');
$img->adaptive_resize(100, 50);
PHP Warning: imagecolorsforindex(): Color index 255 out of range in /.../vendor/abeautifulsite/simpleimage/src/abeautifulsite/SimpleImage.php on line 796
PHP Stack trace:
PHP 1. {main}() php shell code:0
PHP 2. abeautifulsite\SimpleImage->adaptive_resize() php shell code:1
PHP 3. abeautifulsite\SimpleImage->thumbnail() /.../vendor/abeautifulsite/simpleimage/src/abeautifulsite/SimpleImage.php:79
PHP 4. abeautifulsite\SimpleImage->fit_to_width() /.../vendor/abeautifulsite/simpleimage/src/abeautifulsite/SimpleImage.php:1032
PHP 5. abeautifulsite\SimpleImage->resize() /.../vendor/abeautifulsite/simpleimage/src/abeautifulsite/SimpleImage.php:395
PHP 6. imagecolorsforindex() /.../vendor/abeautifulsite/simpleimage/src/abeautifulsite/SimpleImage.php:796
I would love to add two methods that do what Color Thief does.
While there is a PHP adaptation available, it would need some simplification and consolidation to make it into SimpleImage. There may also be a licensing issue that would require the author's permission.
The two methods I propose for this are:
get_dominant_color()
- Given any image, returns the most dominant color as determined by the algorithm.
get_palette()
- Given any image, returns an array of the most commonly used colors.
The return values for each color could be either a hex string or an array of RGB.
I need a "create" method, so I can do this:
$img = new SimpleImage('image.jpg');
$img->flip('x');
$background = new SimpleImage();
$background->create(500, 500, "#ffffff" )->overlay($img, 'bottom right', .5, -10, -10);
Thx.
Trying to load a .GIF
triggers the following error:
[Warning (PHP)] [Message:]exif_read_data(3.gif) [<a href='function.exif-read-data'>function.exif-read-data</a>]: File not supported [File:]/lib/simpleimage.inc.php [Line:]67
The load
method is calling exif_read_data
, however, this function only works with JPEG
and TIFF
according to the manual (http://php.net/manual/en/function.exif-read-data.php).
I didn't see any mention of this in the README or past Issues so I hope I'm not missing something! Seems like it should check for supported file types before trying to load exif data.
I'm having an issue where I'm trying to print several lines (paragraph that contains 3 lines).
$lines = array('this is a nice first line', 'Hey! This is a second line', 'Perhaps this time it will work fine.');
$num = 0;
foreach($lines as $line) {
$img->text($line, 'arvo.ttf', 25, '#ffffff', 'top left', 25, $padding['line']*$num);
$num++;
}
The idea is to have a nicely printed paragraph with lines that have a fixed height.
The issue is that since SimpleImage's text box is automatically calculated, the height varies because some letters and signs are taller than others, as a result (in this particularly example) I get a not so nice-to-see paragraph with chaotic line separations.
It would be great to have a fixed height parameter.
Hi, it's a New Feature request. I need to bestfit all images to 800x500 but also to make their size 800x500 by adding white space where it's needed. I mean, every image proportion is different to the final size and I need to keep it, so, an 1600x700 image after bestfit(800,500) is going to be 800x350. In order to make it 800x500 I need to add 150px of white on the sides, 75 white on the left and 75 white on the right, so it ends 800x500 keeping proportion.
It can be "underlay" but because the current image can be different to png it doesn't work, so, what about "border", something like border(img,A,B,#color,center center) where the image keeps it's size but grows up to AxB with #color around?
Hey,
I am saving a .jpg image with a width of 1700px:
$img->fit_to_width(1700)->save($new_file, 100);
Even though quality is set to 100, the result is very blurred.
Do you have any idea what could be the reason/a solution?
Thanks!
$img = 'img/galerija/'.$entry;
$img = new abeautifulsite\SimpleImage($img);
$img->resize(100, 100)->save("thumb/".$entry);
It ends up with error "Unable to save image: thumb/zed.png"
It does open image, but cant save it. folder thumb is in folder "galerija".
even if trying to save it in same folder $img->resize(100, 100)->save($entry); it returns the same error...
Any Idea why is this cosign me so much trouble ?
This is something I've been meaning to get around to. The library itself is pretty handy, but having inadequate documentation will limit its reach. I'd love to get a little mini-site setup with better usage/examples.
Since SimpleImage is in form of composer package, it would be great to see it on packagist.org to have possibility of installation with composer.
This is so nice class.
May be this feature is already present and I am not able to find it from documentation.
I just need to show error image instead of text as in following code:
try {
$img = new SimpleImage('image.jpg');
$img->flip('x')->output();
} catch(Exception $e) {
$img = new SimpleImage(null, 200, 100, '#000');
$img->text('Error: ' . $e->getMessage())->output();
}
So basically I am asking to add a feature to add a function to convert text to image (using any default font) without a need of an existing image file. I am doing it now in this way, but it would be better if the class have such a function.
} catch(Exception $e) {
header('Content-Type: image/jpeg');
$im = imagecreatetruecolor(200, 100);
$text_color = imagecolorallocate($im, 180, 180, 180);
imagestring($im, 1, 5, 5, 'Error: ' . $e->getMessage(), $text_color);
imagejpeg($im);
imagedestroy($im);
}
Hi, I've been trying to generate images on the fly but I can't make it work.
$img = new SimpleImage();
$img->load("path/to/my/image.jpg");
$img->resize(100,100);
$img->output();
Whether i output it in an or echo it, it only ouput a bunch of weird typos and this message "imagedestroy(): 168 is not a valid Image resource"
What am I doing wrong here ?
Hi,
I am using this library and it is working fine for all other methods except image manipulation on the fly.
Following is the Code i am using:
$extImage = new SimpleImage();
if (file_exists('86gximedia_logo.png')){
$extImage->load('86gximedia_logo.png');
$extImage->resize(100,100);
echo $extImage->output();
}
Can you please help me in achieving this?
Thanks
Hey,
How to center TEXT in image depending on the sizes of the image and width of text ?
Like this:
$img->load('cadre.png')->text("Making simple test\n with SimpleImage Class", DIR.'/delicious.ttf', 25, '#FFFFFF', 'center',0,-45)->output();
If i change text to: "Making Another simple test\n with SimpleImage Class (Github)"
How to get it centered and fully displayed !
Thank you.
First: sorry for my english. I use function "thumbnail" to resize image in the box. When i set width and height to 100px, it work great. But, when i set width and height to 128px i got image 127x128px.
Oryginal: 1000x667 / JPG
$img->thumbnail(128,128)->output();
Same problem when i set 123px or 124px or 228px.
Thanks for your amazing work.
Wonderful job! Very useful and elegant code. I added another function that will trim one side and resize. Like best_fit() but results in exact width and height:
//
// Smart crop (great for non square thumbnails)
// Result in exact width and height by trimming one side
//
// $width - the width of the resulting image
// $height - the height of the resulting image
//
public function smart_crop($width, $height) {
$aspect_ratio = $this->width / $this->height;
$aspect_ratio_required = $width / $height;
if ($aspect_ratio < $aspect_ratio_required) {
// cut the height to achieve desired ratio
$newHeight = $this->height * $aspect_ratio / $aspect_ratio_required;
$x_offset = 0;
$y_offset = ( $this->height - $newHeight ) / 2;
// Trim to correct ratio
$this->crop($x_offset, $y_offset, $this->width, $y_offset + $newHeight);
} elseif ($aspect_ratio > $aspect_ratio_required) {
// cut the width to achieve desired ratio
$newWidth = $this->width / $aspect_ratio * $aspect_ratio_required;
$y_offset = 0;
$x_offset = ( $this->width - $newWidth ) / 2;
// Trim to correct ratio
$this->crop($x_offset, $y_offset, $x_offset + $newWidth, $this->height);
}
// Resize
$this->resize($width, $height);
return $this;
}
Great class by the way.
It would be useful if there was a simple method to replace a color with transparent (for example strip out white background of an image)
I'm writing a script that will re-sizing images and save on server, but to prevent some more process, at the first time, I want to resize, save and send image resized directly to the client browser.
I suggest to create an method like: "output"...
Just an FYI - I fixed this by wrapping $format in strtolower() in the switch( $format ) statement (line 99):
switch( strtolower( $format ) )
Same as what is done in output() (line 694).
Cheers
Kayne
I made a quick fix on my site to be able to keep the actual image ratio, by setting either the width or height to 0
I added a simple calculation on thumbnail function. I'm wondering if you could use add this to your solution, or something similar.
// Determine aspect ratios
$current_aspect_ratio = $this->height / $this->width;
// ************************************
// Calculate the missing width or height, with actual ratio, if required
if ($width == 0) {
$width = $height / $current_aspect_ratio;
} else if ($height == 0) {
$height = $width * $current_aspect_ratio;
}
// ************************************
// Calculate new aspect ratio
$new_aspect_ratio = $height / $width;
// Fit to height/width
[....]
Thanks,
Sebastien
$img = new abeautifulsite\SimpleImage(null, 100, 100, array(0,0,0,127) );
Always returns the black background, I changed the line 137 to work perfectly:
of:
imagefilledrectangle($this->image, 0, 0, $this->width, $this->height, $fill_color);
to:
imagefill($this->image, 0, 0, $fill_color);
What do looks speaks in php manual:
http://www.php.net/manual/pt_BR/function.imagefilledrectangle.php
I wanted to clear an image, and set it to full transparent.
imagefilledrectangle() seems to ignore alpha channel and alpha blending.
Use imagefill() instead
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.