Crop image using php and jquery - php

This code is use to save a cropped image in the same place.
In this code crop image from specific point the datax is x point of canvas
top position where crop start and
datay is y point of canvas top position and
datawidth is width of canvas
dataheight is height of canvas
img_scr path of file
canvas use for crop image
Below is the code described above:
$targ_w = 396; // set the width of the new image
$targ_h =400; //set the height og the new image
$src = $_POST['img_src']; //get the image source
$img_r = imagecreatefromjpeg($src); //open the image
$dst_r = imagecreatetruecolor( $targ_w,$targ_h); //create a new image
imagecopyresampled($dst_r,$img_r,0,0,$_POST['datax'],$_POST['datay'],$targ_w,$targ_h,$_POST['datawidth'],$_POST['dataheight']); // create the new image with the specified width and height from jcrop
unlink($src); //delete the old image
imagejpeg($dst_r,$src,100); // save the new image
imagedestroy($img_r);
Before crop
After Crop image is shrinking

Please try below script for cropping image.
<?php
if (isset($_FILES["file"])) {
$tmpFile = $_FILES["file"]["tmp_name"];
$fileName = 'file name';
list($width, $height) = getimagesize($tmpFile);
// check if the file is really an image
if ($width == null && $height == null) {
header("Location: index.php");
return;
}
// resize if necessary
if ($width >= 400 && $height >= 400) {
$image = new Imagick($tmpFile);
$image->thumbnailImage(400, 400);
$image->writeImage($fileName);
}
else {
move_uploaded_file($tmpFile, $fileName);
}
}
It would be helpful...

Related

get Width and height of image php from imageCreateFromBMP($src)

I want to know the image width and height of an image from the return image using imageCreateFromBMP($src) rather than $src. How can i achieve this ?
$src = 'four.bmp'; //src of image
$im = imagecreatefrombmp($src);
list($width, $height) = GetImageSize($im); // it doesnot work though it takes string
echo 'Image width '.$width.'</br>';
echo 'Image height '.$height.'</br>';
imagesx() and imagesy() take an image resource
http://php.net/manual/en/function.imagesx.php
http://php.net/manual/en/function.imagesy.php
Example:
$src = 'four.bmp'; //src of image
$im = imagecreatefrombmp($src);
$width = imagesx($im);
$height = imagesy($im);
echo 'Image width '.$width.'</br>';
echo 'Image height '.$height.'</br>';

How to get the orientation of an image in php

I am doing a project in core php. When i upload images which taken from mobile phone , it will display as inverted images. i am using exif_read_data function to get the orientation of image.and according to its value rotate the image. But i didn't get the orientation of all images.Is there any method to get the orientation of image?
This is the code
$exif_data = #exif_read_data($tmp_name);
if(!empty($exif_data['Orientation'])) {
switch($exif_data['Orientation']) {
case 8:
$image_p = imagerotate($image_p,90,0);
break;
case 3:
$image_p = imagerotate($image_p,180,0);
break;
case 6:
$image_p = imagerotate($image_p,-90,0);
break;
}
}
Well, you can check for the width and height of the image:
list($width, $height) = getimagesize('your-image.jpg'); // or other image ext
if ( $width > $height ) {
// Landscape image
}
elseif ( $width < $height ) {
// Portrait
}
else {
// Square
}
PS:
EXIF headers tend to be present in JPEG/TIFF images .. See here.
Resource for getimagesize() here.

Why does PHP script turn an image on its side?

I have made a PHP script which dynamically creates a photo gallery (on http://benxd.me/art/) using all the images in a directory. It generates thumbnails for each image, and watermarks a high quality image for use in a lightbox.
However, I have a problem: both the watermarking script and the thumbnail script rotate one image (http://benxd.me/assets/img/art/Advance.jpg) 90 degrees counterclockwise.
I have other images uploaded to the directory, so is there a problem with this image that causes it to be rotated by the PHP? Or would it be caused by my scripts?
Here are my scripts for reference:
engine.php - the script which generates the thumbnails and the HTML displayed on the gallery page
<?php
/*========================================
http://www.techrepublic.com/article/create-a-dynamic-photo-gallery-with-php-in-three-steps/
http://stackoverflow.com/questions/38963849/php-exif-data-not-working
https://davidwalsh.name/generate-photo-gallery
========================================*/
/* function: generates thumbnail */
function make_thumb($src,$dest,$desired_width) {
/* read the source image */
$source_image = imagecreatefromjpeg($src);
$width = imagesx($source_image);
$height = imagesy($source_image);
/* find the "desired height" of this thumbnail, relative to the desired width */
$desired_height = floor($height*($desired_width/$width));
/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width,$desired_height);
/* copy source image at a resized size */
imagecopyresized($virtual_image,$source_image,0,0,0,0,$desired_width,$desired_height,$width,$height);
/* create the physical thumbnail image to its destination */
imagejpeg($virtual_image,$dest);
}
/* function: returns files from dir */
function get_files($images_dir,$exts = array('jpg')) {
$files = array();
if($handle = opendir($images_dir)) {
while(false !== ($file = readdir($handle))) {
$extension = strtolower(get_file_extension($file));
if($extension && in_array($extension,$exts)) {
$files[] = $file;
}
}
closedir($handle);
}
return $files;
}
/* function: returns a file's extension */
function get_file_extension($file_name) {
return substr(strrchr($file_name,'.'),1);
}
include("settings.php");
/** generate photo gallery **/
$image_files = get_files($images_dir);
if(count($image_files)) {
$index = 0;
foreach($image_files as $index=>$file) {
$index++;
$thumbnail_image = $thumbs_dir.$file;
if(!file_exists($thumbnail_image)) {
$extension = get_file_extension($thumbnail_image);
if($extension) {
make_thumb($images_dir.$file,$thumbnail_image,$thumbs_width);
}
}
// read EXIF headers
$exif = exif_read_data("$images_dir/$file", "FILE,COMPUTED,ANY_TAG,IFD0,THUMBNAIL,COMMENT,EXIF", true);
//generate HTML
echo '<li class="borderless img"><img src="',$thumbnail_image,'" /></li>';
}
}
?>
image.php - watermarks the high-quality image for use by the lightbox
<?php
/*========================================
http://gazelleincorporated.com/dynamically-adding-a-watermark-to-an-image-using-php
========================================*/
include("settings.php");
//Let's say you sent the filename via the url, i.e. watermark.php?filename=myimage.jpg
$filename=$_REQUEST['n'];
//get the full path to the image:
$imgpath = $images_dir.$filename;
//OK cool, let's start the process of outputting the image with a watermark...
header('content-type: image/jpeg'); //HTTP header - assumes your images in the gallery are JPGs
//$watermarkfile is the filepath for your watermark image as a PNG-24 Transparent (ex: your logo)
$watermarkfile="../assets/img/copyright-trans.png";
//Get the attributes of the watermark file so you can manipulate it
$watermark = imagecreatefrompng($watermarkfile);
//Get the width and height of your watermark - we will use this to calculate where to put it on the image
list($watermark_width,$watermark_height) = getimagesize($watermarkfile);
//Now get the main gallery image (at $imgpath) so we can maniuplate it
$image = imagecreatefromjpeg($imgpath);
//Get the width and height of your image - we will use this to calculate where the watermark goes
$size = getimagesize($imgpath);
//Calculate where the watermark is positioned
//In this example, it is positioned in the lower right corner, 15px away from the bottom & right edges
$dest_x = ($size[0] - $watermark_width) / 2;
$dest_y = ($size[1] - $watermark_height) / 2;
//I used to use imagecopymerge to apply the watermark to the image
//However it does not preserve the transparency and quality of the watermark
//imagecopymerge($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height, 70);
//So I now use this function which works beautifully:
//Refer here for documentation: http://www.php.net/manual/en/function.imagecopy.php
imagecopy($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height);
//Finalize the image:
imagejpeg($image);
//Destroy the image and the watermark handles
imagedestroy($image);
imagedestroy($watermark);
?>
settings.php
<?php
$images_dir = '../assets/img/art/';
$thumbs_dir = '../assets/img/art/thumb/';
$thumbs_width = 325;
?>
Thanks #MarkSetchell , the problem was caused by the image's exif orientation tag. I wasn't even aware such a thing existed! I was able to use JPEG Autorotate to remove the exif orientation tag. My script now displays the image in the correct orientation.

Add image (PNG / JPG) to animated gif (PHP iMagick)

I am using imagick (PHP) version to basically add text and a logo to an animated gif. I have managed to add text which is great. But i am struggling to add an image using the following:
$gif = new Imagick();
$gif->readImage('images/highres/bg/' . $bgimg . '.gif');
foreach ($gif as $frame) {
$img = new Imagick();
$img->readImageBlob($frame);
$canvas->addImage( $img );
//$canvas->compositeImage($img, Imagick::COMPOSITE_DEFAULT, 0, 0); NOT WORKING
$canvas->setImageDelay( $img->getImageDelay() );
//$img->clear();
//Add Logo
//$logo = new Imagick();
//$logo->readImage('images/uploads/155x100.jpg');
//$canvas->compositeImage($logo, Imagick::COMPOSITE_DEFAULT, 500, 500); NOT WORKING
//$canvas->addImage( $logo );
}
Futhermore, i am struggling to position using X,Y coordinates.
Any ideas?
Might this can help you out.
<?php
if (isset($_FILES["file"])) {
$tmpFile = $_FILES["file"]["tmp_name"];
$fileName = ... // determine secure name for uploaded file
list($width, $height) = getimagesize($tmpFile);
// check if the file is really an image
if ($width == null && $height == null) {
header("Location: index.php");
return;
}
// resize if necessary
if ($width >= 400 && $height >= 400) {
$image = new Imagick($tmpFile);
$image->thumbnailImage(400, 400);
$image->writeImage($fileName);
}
else {
move_uploaded_file($tmpFile, $fileName);
}
}

PHP Thumbnail from image from url

I'm using the code, that first checks filenames in folder and then creates url. In the url find it the special line where is an imagefile. It displays correctly image and address, but if images are too big, takes it so long time. Is it possible to create thumbnail and display this instead of image? Thank You!
require_once('simple_html_dom.php');
$files = scandir('files/');
foreach($files as $file) {
if($file == '.' || $file == '..') continue;
$file = basename($file, ".html");
$url = 'http://address.com/test/'.$file;
$html = file_get_html($url);
foreach($html->find('img') as $element) {
if (strpos($element,'address.com') !== false) {
$url = $element->src;
echo $url.'</br>';
echo '<IMG SRC="',$url, '" WIDTH="128" HEIGHT="96" BORDER="0" ALT="" /><br/>';
}
}
}
You want to use CSS clip:rect(50px 218px 155px 82px);
Setting width and height does not decress the ACTUAL image size, so load time will still take just as long. See this article on step by step div creation and css coding.
http://www.seifi.org/css/creating-thumbnails-using-the-css-clip-property.html
Also as a side note, nothing beats ACTUALLY MAKING TUMBNAILS! There are serve side thumbnail generators, but this is the best you'll get with out actually making tumbnails.
I wrote a blog post on How to proportionally resize uploaded images, you should be able to adjust the code from the sample I wrote to do what you want.
Pasting the code below in case my site dies in the future.
<?php
// *snip* Removed form stuff
$image = imagecreatefromjpeg($pathToImage);
// Target dimensions
$max_width = 240;
$max_height = 180;
// Calculate new dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);
$scale = min($max_width/$old_width, $max_height/$old_height);
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
// Create new empty image
$new = imagecreatetruecolor($new_width, $new_height);
// Resample old into new
imagecopyresampled($new, $image,
0, 0, 0, 0,
$new_width, $new_height, $old_width, $old_height);
// Catch the image data
ob_start();
imagejpeg($new, NULL, 90);
$data = ob_get_clean();
// Destroy resources
imagedestroy($image);
imagedestroy($new);
// Output image data
header("Content-type: image/jpeg", true, 200);
echo $data;
You'd probably want to stick this in a function and change it output to a file. Then generate the thumbnail in your foreach loop and link to the thumbnail instead of the original. You should also check if you have already created a thumbnail for an image so you don't do it more than once for each image.

Categories