ive done my research on the net and here as well and i keep on coming up with no answer that can help me:
i have the below code which displays an image from a folder based on a user's location however the image is too big and i need to resize it.
all the scripts that i have tried or read relate to files being uploaded. can anyone push me in the right direction?
thank you.
<?php
print"
<table <td width=\"138\" height=\"73\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">
<tr>
<td align=\"center\" valign=\"middle\"><a href=\"map.php\"><img src=\"" .
esc('img/' . $db_name . '_maps/sm' . $user['location'] . '.png') .
"\" alt=\"Map of systems around {$user['location']}\" /></a></td>
</tr>
</table>
"
?>
My problem arises from the fact that i need to pull the images as:
<img src=\"" .esc('img/' . $db_name . '_maps/sm' . $user['location'] . '.png') . "\" alt=\"Map of systems around {$user['location']}\" /></a>
Wrote a tutorial about this a while ago. Perhaps it can help. It starts with uploading, but most of it is about resizing. Just swap out the usage of the $_FILES array by geting the image type and file name a different way. Here's the code you should need:
// Create image from file
switch(strtolower($_FILES['image']['type']))
{
case 'image/jpeg':
$image = imagecreatefromjpeg($_FILES['image']['tmp_name']);
break;
case 'image/png':
$image = imagecreatefrompng($_FILES['image']['tmp_name']);
break;
case 'image/gif':
$image = imagecreatefromgif($_FILES['image']['tmp_name']);
break;
default:
exit('Unsupported type: '.$_FILES['image']['type']);
}
// Target dimensions
$max_width = 240;
$max_height = 180;
// 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);
// Resize old image into new
imagecopyresampled($new, $image,
0, 0, 0, 0,
$new_width, $new_height, $old_width, $old_height);
// Catch the imagedata
ob_start();
imagejpeg($new, NULL, 90);
$data = ob_get_clean();
// Destroy resources
imagedestroy($image);
imagedestroy($new);
// Set new content-type and status code
header("Content-type: image/jpeg", true, 200);
// Output data
echo $data;
If you want to store the image as a file rather than dumping it to the browser, remove the head and echo part at the end and then swap out the NULL parameter in the imagejpeg call with an actual filename. Hope that helps :)
Here's the code in use: http://samples.geekality.net/image-resize/
You make take a look at gd : http://www.php.net/manual/en/function.imagecopyresized.php
You can try this:
$extension = substr( $img_url, -3 );
$extension = strtolower($extension);
switch ($extension) {
case "jpg":
case "jpeg":
$src_im = createimagefromjpeg($img_url);
break;
case "gif":
$src_im = createimagefromgif($img_url);
break;
case "png":
$src_im = createimagefrompng($img_url);
break;
}
// Get size
$size = GetImageSize($img_url);
$src_w = $size[0];
$src_h = $size[1];
// $width has to be fixed to your wanted width
$dst_w = $width;
$dst_h = round(($dst_w / $src_w) * $src_h);
$dst_im = ImageCreateTrueColor($dst_w, $dst_h);
ImageCopyResampled($dst_im, $src_im, 0, 0, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
ImageJpeg($dst_im);
ImageDestroy($dst_im);
imageDestroy($src_im);
There a simple to use, open source library called PHP Image Magician that has some nice features and documentation.
It uses 100% GD.
Example of basis usage:
$magicianObj = new imageLib('racecar.jpg');
$magicianObj -> resizeImage(100, 200, 'crop');
$magicianObj -> saveImage('racecar_small.png');
If you need more features convert might be a help.
Related
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.
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');
I'm using imagecopyresampled to create thumbnails based on a certain width and height. The problem I'm having is that their height is being squished. What I want is for all thumbnail images to be 140x84 and if their aspect ratio does not match that the top and bottom extra portions of the image are cropped to center.
Here is what I have so far, any ideas would be greatly appreciated.
// Create Thumbnail
$imgsize = getimagesize($targetFile);
switch(strtolower(substr($targetFile, -3))){
case "jpg":
$image = imagecreatefromjpeg($targetFile);
break;
case "png":
$image = imagecreatefrompng($targetFile);
break;
case "gif":
$image = imagecreatefromgif($targetFile);
break;
default:
exit;
break;
}
$width = 140; //New width of image
$height = $imgsize[1]/$imgsize[0]*$width; //This maintains proportions
$x_mid = $width/2; //horizontal middle
$y_mid = $height/2; //vertical middle
$src_w = $imgsize[0];
$src_h = $imgsize[1];
$picture = imagecreatetruecolor($width, $height);
imagealphablending($picture, false);
imagesavealpha($picture, true);
$bool = imagecopyresampled($picture, $image, 0, 0, 0, ($y_mid-(84/2)), $width, $height, $src_w, $src_h);
if($bool){
switch(strtolower(substr($targetFile, -3))){
case "jpg":
header("Content-Type: image/jpeg");
$bool2 = imagejpeg($picture,$file_dir."/thumbs/".$imageName,85);
break;
case "png":
header("Content-Type: image/png");
imagepng($picture,$file_dir."/thumbs/".$imageName);
break;
case "gif":
header("Content-Type: image/gif");
imagegif($picture,$file_dir."/thumbs/".$imageName);
break;
}
}
imagedestroy($picture);
imagedestroy($image);
You need to first work out if you're going to re-size your image based on it's height or width. You'd usually work this out depending if your original image is portrait or landscape, and the orientation of your desired image size. You then need to work out the other edge programmatically from your choice.
Once you have, you can simple resample your original image at (0,0) and the over-hanging image data will be truncated.
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