Imagecrop without saving the image - php

I have a bunch of product preview images, but they are not the same dimensions.
So i wonder, is it possible to crop an image on the go, without saving it?
These two links should show what i mean:
http://xn--nstvedhandel-6cb.dk/alpha_1/?side=vis_annonce&id=12
http://xn--nstvedhandel-6cb.dk/alpha_1/?side=vis_annonce&id=13

Yes it's possible here's how i do it:
//Your Image
$imgSrc = "image.jpg";
list($width, $height) = getimagesize($imgSrc);
$myImage = imagecreatefromjpeg($imgSrc);
// calculating the part of the image thumbnail
if ($width > $height)
{
$y = 0;
$x = ($width - $height) / 2;
$smallestSide = $height;
}
else
{
$x = 0;
$y = ($height - $width) / 2;
$smallestSide = $width;
}
// copying the part into thumbnail
$thumbSize = 100;
$thumb = imagecreatetruecolor($thumbSize, $thumbSize);
imagecopyresampled($thumb, $myImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);
//final output
header('Content-type: image/jpeg');
imagejpeg($thumb);
This is not a verry light operation, like the others i also reccomend you to save the thumbnail after creating it to your file system.
You might wanna check out PHP's GD library.

You might wanna try this simple script: https://github.com/wes/phpimageresize
It also allows for caching, which should help with performance issues.
But I also prefer resizing images and saving them as thumbnails.

It certainly is possible, but what you are wanting to do probably isn't a good idea - here's why.
If you crop an image, save it, you (or rather your server) never needs to do it again. It's not a light operation.
However, if you keep cropping on the fly, your server will have to do that work each and every single time - which is quite inefficient.
As a worst case scenario, why not automatically crop them once to the dimensions you want (rather than doing it manually) and simply save those results?
Lastly, given that it is a store, wouldn't manually cropping them give your products the best possible images - and thereby the best chance of selling them?

Related

How to put a watermark text across the whole image in diagonal position?

I have connected my Google Drive with my website and im getting images in this format: https://googledrive.com/host/{$GoogleID}. What i want to do is to add a text (not image) watermark to all the images im getting from Google Drive. I already tried with:
http://php.net/manual/en/image.examples.merged-watermark.php
http://phpimageworkshop.com/tutorial/1/adding-watermark.html
Both of them dosent work for me or i cant get them to work i dont know why. I will give an example for an image url: https://googledrive.com/host/0B9eVkF94eohMRlBQVENRWE5mc2c
I have also tried the code from this answer, but it dosent work as well. I guess the problem should be that the files i'm getting from Google Drive are not with the file extention and maybe this cause the problem. This is only my guess...
UPDATE:
i managed to show the photo on the website, but how to put the text in diagonal possition across all the photo like this
try to read image with file_get_contents or fopen and create image from string.
$im = imagecreatefromstring(file_get_contents("image url"));
and then use this example: http://php.net/manual/en/image.examples.merged-watermark.php
Thanks to #Durim Jusaj for helping me out with this one and finally i got the answer after a lot of searching and dealing with a lot of problems i will share my knowledge with u guys. So i will post the code and i will explain what is the code doing.
First thing first. Include this function in your file. This function is finding the center of the image. I havent wrote it i found it in the php docs under the comments so maybe it can be done without it or this function can be modified to be better written.
function imagettftext_cr(&$im, $size, $angle, $x, $y, $color, $fontfile, $text)
{
// retrieve boundingbox
$bbox = imagettfbbox($size, $angle, $fontfile, $text);
// calculate deviation
$dx = ($bbox[2]-$bbox[0])/2.0 - ($bbox[2]-$bbox[4])/2.0; // deviation left-right
$dy = ($bbox[3]-$bbox[1])/2.0 + ($bbox[7]-$bbox[1])/2.0; // deviation top-bottom
// new pivotpoint
$px = $x-$dx;
$py = $y-$dy;
return imagettftext($im, $size, $angle, $px, $py, $color, $fontfile, $text);
}
Load the image you want to apply the watermark to. I'm using Google Drive to extract my photos so thats why im using the file_get_contents, if you are the case like mine then use this, BUT otherwise use what is common and if your picture have extension like .jpg or .png you can use imagecreatefromjpeg or imagecreatefrompng. So it should be something like that $im = imagecreatefromjpeg('photo.jpeg'); for example.
$im = imagecreatefromstring(file_get_contents("https://drive.google.com/uc?id=" . $v['GoogleID']));
After that we need to calculate the position of watermark so we want the watermark to be in the center and to auto adjust its size based on the size of the photo. So on the first like we store all the attributes of the image to array. Second and third lines we calculate where is the center of the image (for me dividing it by 2.2 worked great, you can change this if u want to adjust the position. Last line is the size of the watermark according to the size of the image. This is very important as the watermark will be small or very big if u have images with different sizes.
list($width, $height, $type, $attr) = getimagesize("https://drive.google.com/uc?id=" . $v['GoogleID']);
$width = $width / 2.2;
$height = $height / 2.2;
$size = ($width + $height) / 4;
Set the content-type
header('Content-Type: image/png');
Create the image. I dont know why it should be done twice, but im following the php manual.
$im = imagecreatefromstring(file_get_contents("https://drive.google.com/uc?id=" . $v['GoogleID']));
Create some colors. So, if you want your watermark to be transparent (like mine) you have to use imagecolorallocatealpha, otherwise use imagecolorallocate. Last parameter is the transparency. You can google every function name for more info from the php doc.
$black = imagecolorallocatealpha($im, 0, 0, 0, 100);
The text to draw. Simple as that. Write what you want your text to be.
$text = 'nima.bg';
Replace path by your own font path. Put a font in your server so the code can take it (if you dont have already).
$font = 'fonts/ParsekCyrillic.ttf';
Adding all together. Basically you are creating the final image with the water mark with this function. The magic ;)
imagettftext_cr($im, $size, 20, $width, $height, $black, $font, $text);
Now this is the tricky part! If you want to just display the image without saving it to your server you can simply copy and paste this code, but the website will load very slow if you have more then 2-3 images. So, what i suggest you to do it to save the final images to your server and then display it. I know you will have duplicates, but this is the best choice i think.
ob_start();
imagepng($im);
$image = ob_get_contents();
ob_end_clean();
imagedestroy($im);
echo "<img src='data:image/png;base64," . base64_encode($image) . "'>";
}
OR you can save the images to your server and then display them which is much much faster. The best thing you can do is to process all the images create them with the watermark and then display them (so you have them ready to be show when a visitor visit your website).
imagepng($im, 'photo_stamp.png');
imagedestroy($im);
And the final result for me was that.
UPDATE: As of 2017 you can extract the image using this link 'https://drive.google.com/uc?id=(GoogleID)' or you can just use the 'webContentLink' property of the Google_DriveFile Object (it will give you the same link).

Gallery loading slowly [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
Thumbnails in php generated gallery loading slow
Code link can be found on the bottom of the page.
The site is running from 1and1.co.uk linux based system, good enough to load the gallery much faster than it currently does.
The php generated thumbnails are loading a bit slow, can you tell me why?
http://site-perf.com/cgi-bin/show.cgi?id=vz5le19Fp5E
code:
http://satinaweb.com/tmp/functions.txt
Here is crop.php:
$sourceimage = $_GET['a'];
function crop($sourceimage) {
// Draw & resize
header('Content-Type: $imsz[\'mime\']');
list($width, $height) = getimagesize($sourceimage);
if($width > $height){
$new_width = 100;
$new_height = 75;
} else {
$new_width = 75;
$new_height = 100;
}
$image = imagecreatefromjpeg($sourceimage);
$image_p = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image_p);
imagedestroy($image_p);
imagedestroy($image);
}
crop($sourceimage);
If you have questions, please ask!
What you should have noticed from your site-perf graph most is that,
I'm not going to look through all your code, but you have a file called crop.php. This is going to be slow because it (presumably) crops the images on every page load, which takes a relatively long time (made apparent from the site-perf data); for each request, the browser spends most of it's time waiting for the server to respond.
You should consider using a cache folder to store cropped images and serve them up as-is to reduce loading time.
In crop.php, you could do something like this (pseudo code):
IF original image newer than cropped OR cropped doesn't exist
Load original image
Crop original image
Save cropped image to cache folder
ELSE
Serve already-cropped image from cache
ENDIF
Every time you call crop(), you read the image, modify it and spit it out to the client. This is incredibly wasteful, because you need to re-process the image for every request. You're even destroying the image afterwards (not that this makes much difference). Instead, use is_file() with a cache directory, and save the image to disk as well as sending it to the client.
Now, your script might look like this:
$sourceimage = $_GET['a'];
$cache_dir = dirname(__FILE__) . "/cache"; // Cache directory
$cache_file = $cache_dir . '/' . $source_image; // Path to cached image
function crop($sourceimage) {
header('Content-Type: $imsz[\'mime\']');
// If cached version of cropped image doesn't exist, create it
if(!is_file($cache_file)) {
list($width, $height) = getimagesize($sourceimage);
if($width > $height) {
$new_width = 100;
$new_height = 75;
} else {
$new_width = 75;
$new_height = 100;
}
$image = imagecreatefromjpeg($sourceimage);
$image_p = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image_p, $cache_file); // Save image file to disk
} else { // If cached file exists, output to browser without processing
echo file_get_contents($cache_file);
}
}
crop($sourceimage);
This is untested, but should work. Please don't just copy and paste the above code; read through it and make sure you understand how and why it does what it does.
Your page is loading slowly due to HTTP requests being queued.
Although each image is small, the requests are spending a large proportion of their time queued, waiting for other requests to finish before they start, in the worst cases, they are waiting for one and a half seconds before they even start downloading.
The second delay is then caused by the time it takes to create the images.
The actual download was nearly instant after waiting for these other processes.
Queued 1600ms
Waiting 986ms
Download 0ms
Rather than generate the correct sized images every time, why not store the result to be used on subsequent visits - this means the page will be slow once and then much faster all other times.
If the time your script took to crop the images was shorted, the queueing would be shorter too. Here is an example...
Check in a folder for the cropped image
If it exists, serve it (no computation required)
If it doesn't exist, generate it
Save the result in the folder to cache it

Image uploading concept in PHP

how to take image from one folder and rename and re-size the images and move to another folder?
I need to get image from one folder and rename and re-size the same image and move into another folder using php
You will most likely be using gd for resizing the images.
Here is a pretty crappy, but hopefully useful code sample. In this case, $originalName is the name given in the $_FILES array's tmp_name position. I am resizing to a width of 1200 in this case, with the height adapting according to such width. You might (and most likely will) not desire this behavior. This is just some ugly code I used in some courses I taught about 3 years ago, I don't have the newer samples in this computer so you will have to get used to the idea :)
$newDir is where the file will be located. by calling imagejpeg or imagepng and passing the filename as second argument, it means to the function that you wish to save the image in that location.
if ($type == 'image/jpeg') {
$original = imagecreatefromjpeg($originalName);
}
else {
$original = imagecreatefrompng($originalName);
}
$width = imagesx($original);
$height = imagesy($original);
//prepare for creation of image with width of 1000
$new_height = floor($height * (1200 / $width));
// create the 1200 width image
$tmp_img = imagecreatetruecolor(1200, $new_height);
// copy and resize old image into new image
imagecopyresized($tmp_img, $original, 0, 0, 0, 0,
1200, $new_height, $width, $height);
//create a random and unique name to identify (here it isn't that random ;)
$newDir = '/this/is/some/directory/and/filename.';
if ($type == 'image/jpeg') {
imagejpeg($tmp_img, $newDir."jpg");
}
else {
imagepng($tmp_img, $newDir."png");
}
Many file system functions are already built-in with PHP (e.g. rename), and you'll find most of what you need to resize images by using the GD library here.
There are libraries available in PHP for image resize.
Here are some useful links you may like.
http://www.fliquidstudios.com/2009/05/07/resizing-images-in-php-with-gd-and-imagick/
http://php.net/manual/en/book.image.php
PHP/GD - Cropping and Resizing Images
http://net.tutsplus.com/tutorials/php/image-resizing-made-easy-with-php/
Use imagick http://php.net/manual/en/imagick.resizeimage.php
If I were you I would write a PE using a diffent language (one that you might be best used to) to adjust anything of the given image then just feel free to phpexec it to do all the steps you mentioned, you can sit relax and wait for the end result. HHAHAHHA :-)
Use imagick library to resize; it's good.

add canvas if height < X

Sorry my lousy english, I'm sleepy and struggling with this about 3 days ago.
I'm using "slideViewerPro 1.5" to display an image gallery (PHP + JS).
However, this js script forces me to have all the images at the same size.
So, when I have a vertical picture, I would like to add some white canvas to it so it won't get distorted.
I've tried offline, using Irfanview. Won't work.
I've tried hacking up some GD and PHP scripts. Won't work either.
Messing around the slideViewerPro javascript source... neither.
Also... I've read this about 20 times, and still can't figure out if GD is a proper solution.
http://www.rubblewebs.co.uk/imagemagick/GDexamples.php
Can someone enlight me please?!
I hope this helps with using GD:
$im=imagecreatefrompng($filename);
$width=imagesx($im);
$height=imagesy($im);
$newwidth = 550;
$newheight = 325;
$output = imagecreatetruecolor($newwidth, $newheight);
imagecopymerge($output, $im, ($width<550?550-$width:0), ($height<325?325-$height:0), 0, 0, $width, $height,0);
imagepng($output);
imagedestroy($output);
imagedestroy($im);
$filename is the filename, and then we create a blank image of size 550x325 and paste the image onto the new canvas

Crop and rotate images with JS and PHP

Having been Googling for a tool for a few days, I have found nothing apart from Kroppr but there's no way I can commit to using a tool that can't be tested locally before deployment.
All I need is something that can provide the facility for a user to crop and rotate an image, and have the server save it, overriding the original image. There seems to be plenty of cropping tools out there but nothing that can rotate as well.
Is there such a tool?
No one has answered this yet? Hmmm well I think you are going to have a hard time finding a tool that does exactly what you like. I imagine you are looking for something similar to Kroppr, but not tied to a service.
So here are some resources you can use to build one!
http://code.google.com/p/jqueryrotate/
http://raphaeljs.com/
Both of these look like pretty solid libraries that will let you rotate an image.
Use this in conjunction with a cropper. To display what the image will look like.
Now here is the sneaky part. You only need to keep track of 2 things.
1)The selected angle of rotation 0-360
2)The x1, y1, x2, y2 of the crop.
Once you have collected this data, make a call to a php script on your server and pass it the values of the image manipulation (angle, x1, y1, x2, y2) This can be done through a POST via ajax, form submission, or you can even use a GET and just directly send them as variables in the URL
Now do all of the image manipulation in PHP using GD.
<?php
//Incoming infomation. This should be set by $_GET[] or $_POST[] rather than the hardcoded examples.
$x1 = 100;
$y1 = 100;
$x2 = 400;
$y2 = 400;
$degrees = 47;
$filename = 'images/ducks.jpeg';
//find the original image size
$image_info = getimagesize($filename);
$original_width = $image_info[0];
$original_height = $image_info[1];
//calculat what the new image size should be.
$new_width = abs($x2 - $x1);
$new_height = abs($y2 - $y1);
$image_source = imagecreatefromjpeg($filename);
//rotate
$rotate = imagerotate($image_source, $degrees, 0);
//rotating an image changes the height and width of the image.
//find the new height and width so we can properly compensate when cropping.
$rotated_width = imagesx($rotate);
$rotated_height = imagesy($rotate);
//diff between rotated width & height and original width & height
//the rotated version should always be greater than or equal to the original size.
$dx = $rotated_width - $original_width;
$dy = $rotated_height - $original_width;
$crop_x = $dx/2 + $x1;
$crop_y = $dy/2 + $y1;
$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image, $rotate, 0, 0, $crop_x, $crop_y, $new_width, $new_height, $new_width, $new_height);
//save over the old image.
imagejpeg($new_image, $filename);
?>
This is just a quick and dirty example for you to work off of. If you want this to work for image types other than jpeg you will need to do some checking and use the other methods of GD for handling .pngs or .gifs. The rotation and cropping code will remain the same.
The majority of tinkering left is now in the front-end, I will leave that up to you to decide. All you need to capture is a rotation angle and the x,y cropping points.
Hopefully this was helpful. If you need more help on the front-end stuff let me know.
p.s. I would post more links to resources, but apparently I am only allowed to post 2 because my reputation is not high enough yet.
The answer above is really good, but you could take a look at
http://phpthumb.sourceforge.net/ - For croping
http://code.google.com/p/jqueryrotate/ - jQuery rotate (posted above)
These two worked good in all my projects
I have also found another way to crop images using javascript and have the server to effect the changes. please check out this project on git. I am still testing it though, however, I will soon provide some code snippets, whenever I get it perfectly.
Image Cropper

Categories