I have tried a lot of solutions that I have found on internet but nothing is working for me. I am trying to resize and rotate the image depends on exif data but the image is not rotating. Resizing the image is working fine. But the rotation is not working. Below is the function I used to do that.
function resize_imageb($newbfile,$max_resolution){
if(file_exists($newbfile)){
$original_image = imagecreatefromjpeg($newbfile);
$exif = exif_read_data($newbfile, 0, true);
if(!empty($exif['Orientation'])) {
switch($exif['Orientation']) {
case 8:
$original_image = imagerotate($original_image,90,0);
break;
case 3:
$original_image = imagerotate($original_image,180,0);
break;
case 6:
$original_image = imagerotate($original_image,-90,0);
break;
}
}
$original_width = imagesx($original_image);
$original_height = imagesy($original_image);
$ratio = $max_resolution/$original_width;
$new_width = $max_resolution;
$new_height = $original_height * $ratio;
if($new_height > $max_resolution){
$ratio = $max_resolution / $original_height;
$new_height = $max_resolution;
$new_width = $original_width * $ratio;
}
if($original_image){
$new_image = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($new_image, $original_image, 0, 0, 0, 0,$new_width, $new_height, $original_width, $original_height);
imagejpeg($new_image,$newbfile,100);
imagedestroy($original_image);
imagedestroy($new_image);
}
}
}
When I check the resized image the Orientation information is gone from exif data however the original image I have uploaded did had the Orientation information. I am not sure what i am missing or doing wrong. Can someone help me with this?
Instead of doing the 2 part (resize and rotate) in one function, I made two functions one for rotation created by Wes and then for resize. First called the rotation function and then resize function.
Related
In my old PHP apps i used to run a function like the one bellow to create jpeg image thumbnails.
function imageThumbanail() {
$image_src = imagecreatefromjpeg('http://examplesite.com/images/sample-image.jpg');
$thumbnail_width = 180; //Desirable thumbnail width size 180px
$image_width = imagesx($image_src); //Original image width size -> 1080px
$image_height = imagesy($image_src); //Original image height size -> 1080px
$thumbnail_height = floor( $image_height * ( $thumb_width / $image_width ) ); //Calculate the right thumbnail height depends on given thumbnail width
$virtual_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imagecopyresampled($virtual_image, $image_src, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $image_width, $image_height);
header('Content-Type: image/jpeg');
imagejpeg($virtual_image, null, 100);
imagedestroy($virtual_image); //Free up memory
}
The problem is that now i'd like to run a similar function in a laravel 5.6 app, so i created a controller with the exact same function but instead of get as an output the image thumbnail i get question marks and strange diamond icons, something like encoded version of php gd library jpeg image.
I tried to use return response()->file($pathToFile); as laravel documentation describes but i won't store in a location the thumbnail image.
Any ideas?
Thank you in advance!
I recommend you this package is very simple to install and use it and very kind with programming.
Its called Intervention
Intervention package to handle images
You can make a thumbnail very simple like the following :
$img = Image::make('public/foo.jpg')->resize(320, 240)->insert('public/watermark.png');
Resize and crop image by center
No need to install and include any package. Just create a helper in laravel / lumen and put below code in that helper file and use it wherever you want:
function resize_crop_image($max_width, $max_height, $source_file, $dst_dir, $quality = 80){
$imgsize = getimagesize($source_file);
$width = $imgsize[0];
$height = $imgsize[1];
$mime = $imgsize['mime'];
switch($mime){
case 'image/gif':
$image_create = "imagecreatefromgif";
$image = "imagegif";
break;
case 'image/png':
$image_create = "imagecreatefrompng";
$image = "imagepng";
$quality = 7;
break;
case 'image/jpeg':
$image_create = "imagecreatefromjpeg";
$image = "imagejpeg";
$quality = 80;
break;
default:
return false;
break;
}
$dst_img = imagecreatetruecolor($max_width, $max_height);
$src_img = $image_create($source_file);
$width_new = $height * $max_width / $max_height;
$height_new = $width * $max_height / $max_width;
//if the new width is greater than the actual width of the image, then the height is too large and the rest cut off, or vice versa
if($width_new > $width){
//cut point by height
$h_point = (($height - $height_new) / 2);
//copy image
imagecopyresampled($dst_img, $src_img, 0, 0, 0, $h_point, $max_width, $max_height, $width, $height_new);
}else{
//cut point by width
$w_point = (($width - $width_new) / 2);
imagecopyresampled($dst_img, $src_img, 0, 0, $w_point, 0, $max_width, $max_height, $width_new, $height);
}
$image($dst_img, $dst_dir, $quality);
if($dst_img)imagedestroy($dst_img);
if($src_img)imagedestroy($src_img);
}
//usage example
resize_crop_image(100, 100, "test.jpg", "test.jpg");
Code is already tested many times and working well. All the best, save your time and enjoy your life :)
Is there any way to resize the $_FILES["xfile1"]["tmp_name"] before I send it off to the move_uploaded_file() function? I checked every where but nobody seems to use this function after resizing the image.
ADDED*
// Create image from file
switch(strtolower($_FILES['xfile1']['type']))
{
case 'image/jpeg':
$image = imagecreatefromjpeg($_FILES['xfile1']['tmp_name']);
break;
case 'image/png':
$image = imagecreatefrompng($_FILES['xfile1']['tmp_name']);
break;
case 'image/gif':
$image = imagecreatefromgif($_FILES['xfile1']['tmp_name']);
break;
default:
exit('Unsupported type: '.$_FILES['xfile1']['type']);
}
// Delete original file
#unlink($_FILES['image']['tmp_name']);
// Target dimensions
$max_width = 540;
$max_height = 540;
// Get current dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);
// Calculate the scaling we need to do to fit the image inside our frame
$scale = min($max_width/$old_width, $max_height/$old_height);
// Get the new dimensions
$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);
ob_start();
imagejpeg($new,'saved.jpeg' , 90);
$data = ob_get_clean();
So i have this so far. I have this $data variable which i want to replace with $_FILES["xfile1"]["tmp_name"] in the move_uploaded_file() function. Is that possible?
Thanks in Advance.
I'm building a wallpaper website and therefore i need to be able to resize the original image before downloading. I tried this code to resize the image:
//resize and crop image by center
function resize_crop_image($max_width, $max_height, $source_file, $dst_dir, $quality = 80){
$imgsize = getimagesize($source_file);
$width = $imgsize[0];
$height = $imgsize[1];
$mime = $imgsize['mime'];
switch($mime){
case 'image/gif':
$image_create = "imagecreatefromgif";
$image = "imagegif";
break;
case 'image/png':
$image_create = "imagecreatefrompng";
$image = "imagepng";
$quality = 7;
break;
case 'image/jpeg':
$image_create = "imagecreatefromjpeg";
$image = "imagejpeg";
$quality = 80;
break;
default:
return false;
break;
}
$dst_img = imagecreatetruecolor($max_width, $max_height);
$src_img = $image_create($source_file);
$width_new = $height * $max_width / $max_height;
$height_new = $width * $max_height / $max_width;
//if the new width is greater than the actual width of the image, then the height is too large and the rest cut off, or vice versa
if($width_new > $width){
//cut point by height
$h_point = (($height - $height_new) / 2);
//copy image
imagecopyresampled($dst_img, $src_img, 0, 0, 0, $h_point, $max_width, $max_height, $width, $height_new);
}else{
//cut point by width
$w_point = (($width - $width_new) / 2);
imagecopyresampled($dst_img, $src_img, 0, 0, $w_point, 0, $max_width, $max_height, $width_new, $height);
}
$image($dst_img, $dst_dir, $quality);
if($dst_img)imagedestroy($dst_img);
if($src_img)imagedestroy($src_img);
}
And this will do the resize:
resize_crop_image($width, $height, $image_URL, $save_URL)
This code works fine for me but i want to ONLY send the output to user's browser, since saving thousands of extra images isn't possible. There are libraries i can use, but i don't want to use a third party snippet. Is there a way to alter this code in the way i desire?
Thanks.
For your $image function , do not specify a destination directory (null) and an image stream will be created.
header("Content-type:{$mime}");
That should send the image to the user
You just need to set the proper headers and echo the output. Every PHP request "downloads a file" to the browser, more or less. You just need to specify how the browser handles it. So try something like:
header("Content-Type: $mime");
header("Content-Disposition: attachment; filename=$dst_img");
echo $dst_img;
That should do it for you.
Can someone help me out.. I want to check if my resize is working correctly, but I can't output the imagecopyresampled image. It outputs a bunch of weird characters right now.
//uploading image
$image_file = $_FILES['image']['tmp_name'];
$image_size = #getimagesize($image_file);
$image_mime = $image_size['mime'];
$image_width = $image_size['0'];
$image_height = $image_size['1'];
$image_ratio = $image_width/$image_height;
//not an image
if ($image_size === false) {
error('1');
}
//check to see if valid image type
switch ($image_mime){
case 'image/jpg':
case 'image/jpeg':
case 'image/pjpeg':
$image_file = #imagecreatefromjpeg($image_file);
break;
case 'image/png':
$image_file = #imagecreatefrompng($image_file);
break;
default:
error('2');
break;
}
if ($image_width < 450 || $image_height < 350) {
//image too small
error('3');
}
if ($image_ratio >= 1){
//resize by height
$height = 350;
$ratio = $height/$image_height;
$width = $image_width * $ratio;
} else {
//resize by width
$width = 450;
$ratio = $width/$image_width;
$height = $image_height * $ratio;
}
//get the center axis
$x_center = ($image_width - $width)/2;
$y_center = ($image_height - $height)/2;
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $image_file, 0, 0, $x_center, $y_center, $width, $height, $image_width, $image_height);
imagepng($new_image);
exit();
Those weird character are the image as output in binary. Your browser doesn't know that that's supposed to be an image, because you did not tell it. Add a header before the image output to inform the browser what kind of data it's dealing with:
header('Content-Type: image/png');
I have a quick question that I'm not quite sure to set up. I've seen examples elsewhere but nothing specifically like my situation. I would like to resize images using PHP so they're readable and not just wonkily stretched like if you use HTML. If they're not 250 pixels wide, or 160 pixels tall, how can I resize the picture so it's proportionate but fits within that space?
Thanks!
PHP does not manipulate images directly. You will need to use an image manipulation library such as gd or ImageMagick to accomplish this goal.
In ImageMagick, image resizing is accomplished like this:
$thumb = new Imagick('myimage.gif');
$thumb->resizeImage(320,240,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage('mythumb.gif');
With GD, you can do it like this:
<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Output
imagejpeg($image_p, null, 100);
?>
Ok, so below is an Image object that I use in my store. It maintains scale - requires GD
<?php
class Store_Model_Image extends My_Model_Abstract
{
const PATH = STORE_MODEL_IMAGE_PATH;
const URL = "/store-assets/product-images/";
public function get_image_url($width, $height)
{
$old_file = self::PATH . $this->get_filename();
$basename = pathinfo($old_file, PATHINFO_FILENAME);
$new_name = sprintf("%s_%sx%s.jpg", $basename, $width, $height);
if(file_exists(self::PATH . $new_name))
{
return self::URL . $new_name;
}
else
{
list($width_orig, $height_orig, $image_type) = #getimagesize($old_file);
$img = FALSE;
// Get the image and create a thumbnail
switch($image_type)
{
case 1:
$img = #imagecreatefromgif($old_file);
break;
case 2:
$img = #imagecreatefromjpeg($old_file);
break;
case 3:
$img = #imagecreatefrompng($old_file);
break;
}
if(!$img)
{
throw new Zend_Exception("ERROR: Could not create image handle from path.");
}
// Build the thumbnail
if($width_orig > $height_orig)
{
$width_ratio = $width / $width_orig;
$new_width = $width;
$new_height = $height_orig * $width_ratio;
}
else
{
$height_ratio = $height / $height_orig;
$new_width = $width_orig * $height_ratio;
$new_height = $height;
}
$new_img = #imagecreatetruecolor($new_width, $new_height);
// Fill the image black
if(!#imagefilledrectangle($new_img, 0, 0, $new_width, $new_height, 0))
{
throw new Zend_Exception("ERROR: Could not fill new image");
}
if(!#imagecopyresampled($new_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig))
{
throw new Zend_Exception("ERROR: Could not resize old image onto new bg.");
}
// Use a output buffering to load the image into a variable
ob_start();
imagejpeg($new_img, NULL, 100);
$image_contents = ob_get_contents();
ob_end_clean();
// lastly (for the example) we are writing the string to a file
$fh = fopen(self::PATH . $new_name, "a+");
fwrite($fh, $image_contents);
fclose($fh);
return self::URL . $new_name;
}
}
}
I resize the image at request time, so the first time the page loads an image will be resized to the required size for the template. (this means I don't have to crash a shared host trying to regenerate image thumbnails everytime my design changes)
So in the template you pass your image object, and when you need a image thumb,
<img src="<?php echo $image->get_image_url(100, 100); ?>" />
you now have a 100x100 thumb, which is saved to the Server for reuse at a later date
gd and imagemagick are two tools that may work for you
http://php.net/manual/en/book.image.php
http://php.net/manual/en/book.imagick.php
Here is something I used to use
class cropImage{
var $imgSrc,$myImage,$cropHeight,$cropWidth,$x,$y,$thumb;
function setImage($image,$moduleWidth,$moduleHeight,$cropPercent = "1") {
//Your Image
$this->imgSrc = $image;
//getting the image dimensions
list($width, $height) = getimagesize($this->imgSrc);
//create image from the jpeg
$this->myImage = imagecreatefromjpeg($this->imgSrc) or die("Error: Cannot find image!");
if($width > $height) $biggestSide = $width; //find biggest length
else $biggestSide = $height;
//The crop size will be half that of the largest side
//$cropPercent = 1.55; // This will zoom in to 50% zoom (crop)
if(!$cropPercent) {
$cropPercent = 1.50;
}
$this->cropWidth = $moduleWidth*$cropPercent;
$this->cropHeight = $moduleHeight*$cropPercent;
//$this->cropWidth = $biggestSide*$cropPercent;
//$this->cropHeight = $biggestSide*$cropPercent;
//getting the top left coordinate
$this->x = ($width-$this->cropWidth)/2;
$this->y = ($height-$this->cropHeight)/2;
}
function createThumb($moduleWidth,$moduleHeight){
$thumbSize = 495; // will create a 250 x 250 thumb
$this->thumb = imagecreatetruecolor($moduleWidth, $moduleHeight);
//$this->thumb = imagecreatetruecolor($thumbSize, $thumbSize);
imagecopyresampled($this->thumb, $this->myImage, 0, 0,$this->x, $this->y, $moduleWidth, $moduleHeight, $this->cropWidth, $this->cropHeight);
//imagecopyresampled($this->thumb, $this->myImage, 0, 0,$this->x, $this->y, $thumbSize, $thumbSize, $this->cropWidth, $this->cropHeight);
}
function renderImage(){
header('Content-type: image/jpeg');
imagejpeg($this->thumb);
imagedestroy($this->thumb);
}
}
Call it by using
$image = new cropImage;
$image->setImage($imagepath,$moduleWidth,$moduleHeight,$scaleRelation);
$image->createThumb($moduleWidth,$moduleHeight);
$image->renderImage();
Use GD or ImageMagick. Here you may find a real production example of code (used by MediaWiki) that supports consoled ImageMagick interface (transformImageMagick method), ImageMagick extension interface (transformImageMagickExt method) and GD (transformGd method).
There a simple to use, open source library called PHP Image Magician that will can help you out.
Example of basis usage:
$magicianObj = new imageLib('racecar.jpg');
$magicianObj -> resizeImage(100, 200, 'crop');
$magicianObj -> saveImage('racecar_small.png');