How to get the orientation of an image in php - 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.

Related

Crop a png image with PHP, remove empty transparency

I'm currently trying to work with pictures and PHP, thanks to GD functions.
Now I would like to modify the size of PNG pictures. Here is an example of a PNG I'd like to resize :
The dotted line represent the border of the PNG, the background is transparent, and I only have a star lost on the middle of a large space. I'd like to crop this star, to get a simple square of the star (even if the new background becomes blank, It doesn't matter).
How could I do something like that efficiently ? I thought about doing a loop checking every pixel of the picture.. Trying to find where the image is, to finally crop with a little margin based on the minimum x / maximum X and minimum y / maximum y values, but If I start working with hundreds of pictures, It would be really long.
EDIT :
<?php
$file = "./crop.png";
$ext = pathinfo($file, PATHINFO_EXTENSION);
$image;
switch ($ext){
case 'png':
$image = imagecreatefrompng($file);
break;
case 'jpeg':
case 'jpg':
$image = imagecreatefromjpeg($file);
break;
case 'gif':
$image = imagecreatefromgif($file);
break;
}
$cropped = imagecropauto($image, IMG_CROP_DEFAULT);
if ($cropped !== false) { // in case a new image resource was returned
echo "=> Cropping needed\n";
imagedestroy($image); // we destroy the original image
$image = $cropped; // and assign the cropped image to $im
}
imagepng($image, "./cropped.png");
imagedestroy($image);
If you read and follow the php php-gd documentation, you'll find a function called imagecropauto which does exactly what you want, it crops the alpha channel of the image.
Crop an PNG image with alpha channel
$im = imagecreatefrompng("./star-with-alpha.png");
$cropped = imagecropauto($im, IMG_CROP_DEFAULT);
if ($cropped !== false) { // in case a new image resource was returned
imagedestroy($im); // we destroy the original image
$im = $cropped; // and assign the cropped image to $im
}
imagepng($im, "./star-with-alpha-crop.png");
imagedestroy($im);
You can try it dirrectly to a php page using this code:
<body>
<img src="star-with-alpha.png">
<?php
$im = imagecreatefrompng("./star-with-alpha.png");
$cropped = imagecropauto($im, IMG_CROP_DEFAULT);
if ($cropped !== false) { // in case a new image resource was returned
imagedestroy($im); // we destroy the original image
$im = $cropped; // and assign the cropped image to $im
}
imagepng($im, "./star-with-alpha-crop.png");
imagedestroy($im);
?>
<img src="star-with-alpha-crop.png">
</body>
The result
http://zikro.gr/dbg/php/crop-png/
[This is for ubuntu 12]
The only problem with the imagecropauto is that it works only on Mac & Windows.
And since most of the servers today use ubuntu/debain - this function is of no use.
Instead use Imagick() for this.
Here is a sample code I wrote which does exactly this:
//Add background transmparent
$background = 'none';
$image = new Imagick($path);
$image->trimImage(0);
//add transparent border
//border add start
/** Set border format **/
$borderWidth = 20;
$borderColor = 'none';
$borderPadding = 10;
$imageWidth = $image->getImageWidth() + ( 2 * ( $borderWidth +
$borderPadding ) );
$imageHeight = $image->getImageHeight() + ( 2 * ( $borderWidth +
$borderPadding ) );
Create Imagick object for final image with border
$imageWithBorder = new Imagick();
// Set image canvas
$imageWithBorder->newImage( $imageWidth, $imageHeight, new ImagickPixel(
'none' ));
// Create ImagickDraw object to draw border
$border = new ImagickDraw();
// Set fill color to transparent
$border->setFillColor( 'none' );
// Set border format
$border->setStrokeColor( new ImagickPixel( $borderColor ) );
$border->setStrokeWidth( $borderWidth );
$border->setStrokeAntialias( false );
Draw border
$border->rectangle(
$borderWidth / 2 - 1,
$borderWidth / 2 - 1,
$imageWidth - ( ($borderWidth / 2) ),
$imageHeight - ( ($borderWidth / 2) )
);
// Apply drawed border to final image
$imageWithBorder->drawImage( $border );
$imageWithBorder->setImageFormat('png');
Save Image
// Put source image to final image
$imageWithBorder->compositeImage(
$image, Imagick::COMPOSITE_DEFAULT,
$borderWidth + $borderPadding,
$borderWidth + $borderPadding
);
$imageWithBorder->writeImage($path);
Recenter and fit to original image height and width
$imageWithBorder->scaleImage(FINAL_WIDTH, FINAL_HEIGHT, true);
$imageWithBorder->setImageBackgroundColor($background);
$w = $imageWithBorder->getImageWidth();
$h = $imageWithBorder->getImageHeight();
$imageWithBorder->extentImage(FINAL_WIDTH, FINAL_HEIGHT, ($w -
FINAL_WIDTH) / 2, ($h - FINAL_HEIGHT)/ 2);
$imageWithBorder->writeImage($path);
Hope it helps.
Cheers!

Crop image using php and jquery

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...

Cannot get exif imagetype data on specific jpeg image

I have a .jpg image (cjonline.com/sites/default/files/13183951.jpg) from a specific url that I cannot get the image size for because it will not process the exif data or getimagesize functions. I am able to get data for all other .jpg images just fine and I can't seem to understand why this one keeps failing. It loads fine in a browser.
$image = 'http://cjonline.com/sites/default/files/13183951.jpg';
try {
if ($image !== '') {
// Gets image width and length
switch (#exif_imagetype($image))
{
case 1: // gif -> jpg
$img = imagecreatefromgif($image);
break;
case 2: // jpeg -> jpg
$img = imagecreatefromjpeg($image);
break;
case 3: // png -> jpg
$img = imagecreatefrompng($image);
break;
default:
$img = '';
return array(0,0);
}
$imgWidth = imagesx($img);
$imgHeight = imagesy($img);
}
}
catch(Exception $e) { $img = ''; }
return array($imgWidth, $imgHeight);
You can get size with this:
list($width, $height) = getimagesize($image_file);

PHP Image cropping to square

I was using the following PHP script to create square thumbnails which I got here http://www.abeautifulsite.net/blog/2009/08/cropping-an-image-to-make-square-thumbnails-in-php/
I was able to integrate this into my image upload script, which uploads full sized image and after that takes the uploaded image and creates a thumbnail from that.
The problem is the author of the script said, it will crop landscape and portrait images without problem. It crops landscape images perfectly, but as it faces portrait image, the output thumbnail will not be cropped, but it appears scaled down to fit the given square thumbnail height and the emtpy space on the sides will be filled with black color.
I know there is a way to fix this, but as I am relatively new to PHP I am not able to solve it.
Can someome with real experience in PHP fix this?
Thank you in advance!
The script is here:
$
function square_crop($src_image, $dest_image, $thumb_size = 64, $jpg_quality = 90) {
// Get dimensions of existing image
$image = getimagesize($src_image);
// Check for valid dimensions
if( $image[0] <= 0 || $image[1] <= 0 ) return false;
// Determine format from MIME-Type
$image['format'] = strtolower(preg_replace('/^.*?\//', '', $image['mime']));
// Import image
switch( $image['format'] ) {
case 'jpg':
case 'jpeg':
$image_data = imagecreatefromjpeg($src_image);
break;
case 'png':
$image_data = imagecreatefrompng($src_image);
break;
case 'gif':
$image_data = imagecreatefromgif($src_image);
break;
default:
// Unsupported format
return false;
break;
}
// Verify import
if( $image_data == false ) return false;
// Calculate measurements
if( $image[0] & $image[1] ) {
// For landscape images
$x_offset = ($image[0] - $image[1]) / 2;
$y_offset = 0;
$square_size = $image[0] - ($x_offset * 2);
} else {
// For portrait and square images
$x_offset = 0;
$y_offset = ($image[1] - $image[0]) / 2;
$square_size = $image[1] - ($y_offset * 2);
}
// Resize and crop
$canvas = imagecreatetruecolor($thumb_size, $thumb_size);
if( imagecopyresampled(
$canvas,
$image_data,
0,
0,
$x_offset,
$y_offset,
$thumb_size,
$thumb_size,
$square_size,
$square_size
)) {
// Create thumbnail
switch( strtolower(preg_replace('/^.*\./', '', $dest_image)) ) {
case 'jpg':
case 'jpeg':
return imagejpeg($canvas, $dest_image, $jpg_quality);
break;
case 'png':
return imagepng($canvas, $dest_image);
break;
case 'gif':
return imagegif($canvas, $dest_image);
break;
default:
// Unsupported format
return false;
break;
}
} else {
return false;
}
}
?>
And I call it like this - square_crop('source_image', 'destination_image', 65);
You can see the result here http://imageshack.us/photo/my-images/717/imgfl.png/
It happens only with portrait images, landscape images are cropped in a way that it fills the whole square.
For cropping only, replace the imagecopyresampled() function with imagecopy().
The resampled performs an appropriate stretching or shrinking of the image if the source and destination coordinates and width and heights differ. imagecopy() doesn't.
you should add an image ration inside the if() statement, so it will understand if it's portrait or landscape.
change the line below
// Calculate measurements
if( $image[0] > $image[1] ) {

PHP upload and resize image

I am working on a script that uploads a picture using PHP and I wanna make it resize the image to width 180 before saving it.
I tried using the WideImage library and ->saveFileTO(...) but when I include the WideImage.php in the page, the page goes blank !!
So here is my script if you can help me and tell me how to make it save the resized version
You can use the PHP GD library to resize an image on upload.
The following code should give you an idea of how to implement the resize:
// Get the image info from the photo
$image_info = getimagesize($photo);
$width = $new_width = $image_info[0];
$height = $new_height = $image_info[1];
$type = $image_info[2];
// Load the image
switch ($type)
{
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($photo);
break;
case IMAGETYPE_GIF:
$image = imagecreatefromgif($photo);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($photo);
break;
default:
die('Error loading '.$photo.' - File type '.$type.' not supported');
}
// Create a new, resized image
$new_width = 180;
$new_height = $height / ($width / $new_width);
$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Save the new image over the top of the original photo
switch ($type)
{
case IMAGETYPE_JPEG:
imagejpeg($new_image, $photo, 100);
break;
case IMAGETYPE_GIF:
imagegif($new_image, $photo);
break;
case IMAGETYPE_PNG:
imagepng($new_image, $photo);
break;
default:
die('Error saving image: '.$photo);
}
You can use a class I've written for just such a task:
http://code.google.com/p/image2/source/browse/#svn/trunk/includes/classes
<?php
try
{
$image = new Image2($path_to_image);
}
catch (NotAnImageException $e)
{
printf("FILE PROVIDED IS NOT AN IMAGE, FILE PATH: %s", $path_to_image);
}
$image -> resize(array("width" => 180)) -> saveToFile($new_path); // be sure to exclude the extension
$new_file_location = $image -> getFileLocation(); // this will include the extension for future use
You don't even need to use the WideImage library.
Check this script here:
http://bgallz.org/502/php-upload-resize-image/
You start by uploading the image and saving to a temp image file. This script runs off a form with inputs for the max height or max width. So it will then generate a new image file based on the new width/height and then copy the temp image onto the new one created on the server.
You see this with the following code:
// Create temporary image file.
$tmp = imagecreatetruecolor($newwidth,$newheight);
// Copy the image to one with the new width and height.
imagecopyresampled($tmp,$image,0,0,0,0,$newwidth,$newheight,$width,$height);
Dont use any library
Check this script
http://dr-wordpress.blogspot.com/2013/12/image-resizing-using-php.html
Just gave the quality of imges from (0-99)
this code will automatically resize the images while uploading

Categories