Using the following script I´m getting over-compressed images on the front end. They appear fine on the server, but the imagesize.php seems to be destroying the end result. Here is a visual of the issue (ignore the slight difference in size on this image, that's my bad alignment) http://puu.sh/38VaP.png. Any ideas? Here is the script...
<?php
// Get the File path for the image
$imagedir = '../../imgs';
$imagename = $_GET["file"];
$sImagePath = "$imagedir/$imagename";
// If you want exact dimensions, you
// will pass 'width' and 'height'
$iThumbnailWidth = (int)$_GET['width'];
$iThumbnailHeight = (int)$_GET['height'];
// If you want proportional thumbnails,
// you will pass 'maxw' and 'maxh'
$iMaxWidth = (int)$_GET["maxw"];
$iMaxHeight = (int)$_GET["maxh"];
// Based on the above we can tell which
// type of resizing our script must do
if ($iMaxWidth && $iMaxHeight) $sType = 'scale';
else if ($iThumbnailWidth && $iThumbnailHeight) $sType = 'exact';
// The 'scale' type will make the image
// smaller but keep the same dimensions
// The 'exact' type will make the thumbnail
// exactly the width and height you choose
// To start off, we will create a copy
// of our original image in $img
$img = NULL;
// At this point, we need to know the
// format of the image
// Based on that, we can create a new
// image using these functions:
// - imagecreatefromjpeg
// - imagecreatefrompng
// - imagecreatefromgif
//$sExtension = strtolower(end(explode('.', $sImagePath)));
$explodedImagePath = explode('.',$sImagePath);
$sExtension = strtolower(end($explodedImagePath));
if ($sExtension == 'jpg' || $sExtension == 'jpeg') {
$img = #imagecreatefromjpeg($sImagePath)
or die("Cannot create new JPEG image");
} else if ($sExtension == 'png') {
$img = #imagecreatefrompng($sImagePath)
or die("Cannot create new PNG image");
} else if ($sExtension == 'gif') {
$img = #imagecreatefromgif($sImagePath)
or die("Cannot create new GIF image");
}
// If the image has been created, we may proceed
// to the next step
if ($img) {
// We now need to decide how to resize the image
// If we chose to scale down the image, we will
// need to get the original image propertions
$iOrigWidth = imagesx($img);
$iOrigHeight = imagesy($img);
if ($sType == 'scale') {
// Get scale ratio
$fScale = min($iMaxWidth/$iOrigWidth,
$iMaxHeight/$iOrigHeight);
// To explain how this works, say the original
// dimensions were 200x100 and our max width
// and height for a thumbnail is 50 pixels.
// We would do $iMaxWidth/$iOrigWidth
// (50/200) = 0.25
// And $iMaxHeight/$iOrigHeight
// (50/100) = 0.5
// We then use the min() function
// to find the lowest value.
// In this case, 0.25 is the lowest so that
// is our scale. The thumbnail must be
// 1/4th (0.25) of the original image
if ($fScale < 1) {
// We must only run the code below
// if the scale is lower than 1
// If it isn't, this means that
// the thumbnail we want is actually
// bigger than the original image
// Calculate the new height and width
// based on the scale
$iNewWidth = floor($fScale*$iOrigWidth);
$iNewHeight = floor($fScale*$iOrigHeight);
// Create a new temporary image using the
// imagecreatetruecolor function
$tmpimg = imagecreatetruecolor($iNewWidth,
$iNewHeight);
// The function below copies the original
// image and re-samples it into the new one
// using the new width and height
imagecopyresampled($tmpimg, $img, 0, 0, 0, 0,
$iNewWidth, $iNewHeight, $iOrigWidth, $iOrigHeight);
// Finally, we simply destroy the $img file
// which contained our original image
// so we can replace with the new thumbnail
imagedestroy($img);
$img = $tmpimg;
}
} else if ($sType == "exact") {
// Get scale ratio
$fScale = max($iThumbnailWidth/$iOrigWidth,
$iThumbnailHeight/$iOrigHeight);
// This works similarly to other one but
// rather than the lowest value, we need
// the highest. For example, if the
// dimensions were 200x100 and our thumbnail
// had to be 50x50, we would calculate:
// $iThumbnailWidth/$iOrigWidth
// (50/200) = 0.25
// And $iThumbnailHeight/$iOrigHeight
// (50/100) = 0.5
// We then use the max() function
// to find the highest value.
// In this case, 0.5 is the highest so that
// is our scale. This is the first step of
// the image manipulation. Once we scale
// the image down to 0.5, it will have the
// dimensions of 100x50. At this point,
// we will need to crop the image, leaving
// the height identical but halving
// the width to 50
if ($fScale < 1) {
// Calculate the new height and width
// based on the scale
$iNewWidth = floor($fScale*$iOrigWidth);
$iNewHeight = floor($fScale*$iOrigHeight);
// Create a new temporary image using the
// imagecreatetruecolor function
$tmpimg = imagecreatetruecolor($iNewWidth,
$iNewHeight);
$tmp2img = imagecreatetruecolor($iThumbnailWidth,
$iThumbnailHeight);
// The function below copies the original
// image and re-samples it into the new one
// using the new width and height
imagecopyresampled($tmpimg, $img, 0, 0, 0, 0,
$iNewWidth, $iNewHeight, $iOrigWidth, $iOrigHeight);
// Our $tmpimg will now have the scaled down
// image. The next step is cropping the picture to
// make sure it's exactly the size of the thumbnail
// The following logic choose how the image
// will be cropped. Using the previous example, it
// needs to take a 50x50 block from the original
// image and copy it over to the new thumbnail
// Since we want to copy the exact center of the
// scaled down image, we need to find out the x
// axis and y axis. To do so, say the scaled down
// image now has a width of 100px but we want it
// to be only 50px
// Somehow, we need to select between the 25th and
// 75th pixel to copy the middle.
// To find this value we do:
// ($iNewWidth/2)-($iThumbnailWidth/2)
// ( 100px / 2 ) - (50px / 2)
// ( 50px ) - ( 25px )
// = 25px
if ($iNewWidth == $iThumbnailWidth) {
$yAxis = ($iNewHeight/2)-
($iThumbnailHeight/2);
$xAxis = 0;
} else if ($iNewHeight == $iThumbnailHeight) {
$yAxis = 0;
$xAxis = ($iNewWidth/2)-
($iThumbnailWidth/2);
}
// We now have to resample the new image using the
// new dimensions are axis values.
imagecopyresampled($tmp2img, $tmpimg, 0, 0,
$xAxis, $yAxis,
$iThumbnailWidth,
$iThumbnailHeight,
$iThumbnailWidth,
$iThumbnailHeight);
imagedestroy($img);
imagedestroy($tmpimg);
$img = $tmp2img;
}
}
// Display the image using the header function to specify
// the type of output our page is giving
header("Content-type: image/jpeg");
imagejpeg($img);
}
?>
You can adjust the compression level using the third parameter to imagejpeg. For top quality (but biggest file size) use:
imagejpeg($img, NULL, 100);
A quality value of 90 will probably give you a reasonable balance between quality and file size.
Then again, the kind of image you have in the example may be best saved as PNG, with imagepng. The JPEG format is best used for photographic images.
Looks like you're destroying the image yourself:
imagedestroy($tmpimg);
$img = $tmp2img;
... snip ...
imagejpeg($tmpimg);
You cannot imagedestroy() until AFTER you have completely finished using the GD image handle, which includes outputting it via imagejpeg. once it's destroyed, the image is GONE from memory and the handle variable becomes invalid.
Related
I'm am trying to add a 50px white margin down the right side of an image by creating an empty image that's 50px wider than the source image and then merging the source image onto it. The problem is that the source image just gets stretched sideways so it's 50px wider!
Maybe I'm using the wrong function to merge the images ...
here's my code
$destImage = $filepath;
#echo "dest image = ".$destImage;
$sourceImage = imagecreatefrompng($filepath);
// dimensions
$src_wide = imagesx($sourceImage);
echo "src_wide=".$src_wide;
$src_high = imagesy($sourceImage);
// new image dimensions with right padding
$dst_wide = $src_wide+50;
echo "dst_wide=".$dst_wide;
$dst_high = $src_high;
// New resource image at new size
$dst = imagecreatetruecolor($dst_wide, $dst_high);
// set white padding color
$clear = array('red'=>255,'green'=>255,'blue'=>255);
// fill the image with the white padding color
$clear = imagecolorallocate( $dst, $clear["red"], $clear["green"], $clear["blue"]);
imagefill($dst, 0, 0, $clear);
// copy the original image on top of the new one
imagecopymerge($dst,$sourceImage,0,0,0,0,$src_wide,$src_high, 100);
imagepng($dst,$destImage,6);
imagedestroy($dst);
chmod($destImage,0775);
what am I doing wrong here ??
thanks
It's stretching because you are copying it to the full width of the destination image. Instead use
imagecopyresampled($dst,$sourceImage,50,0,0,0,$src_wide,$src_high,$src_wide,$src_high);
When i submit a new image to database which is extracted from pdf,it should be cropped image of original image. If the image already exists in database, than image should not be inserted and if its not inserted,i have to generate an identification value for that.
The identification value will also be inserted to the same table as of image.
There are keys involved. table page have the following identies
pid,qid,pidentifierval,image
$record = array('pid' => "NULL",
'qid' => $qid,
'pidentifierval' => $pid,
'image' => $crop,
'rotation' => 0);
function newquestionnaire($filename,$desc = "",$type="pngmono"){
global $db;
if ($desc == "") $desc = $filename;
//generate temp file
$tmp = tempnam(TEMPORARY_DIRECTORY, "FORM");
//print "Creating PNG files<br/>";
//use ghostscript to convert to PNG
exec(GS_BIN . " -sDEVICE=$type -r300 -sOutputFile=\"$tmp\"%d.png -dNOPAUSE -dBATCH \"$filename\"");
//add to questionnaire table
//
//create form entry in DB
//
$db->StartTrans();
$sql = "INSERT INTO questionnaires (qid,description,sheets)
VALUES (NULL,'$desc',0)";
$db->Execute($sql);
$qid = $db->Insert_Id();
//Number of imported pages
$pages = 0;
//read pages from 1 to n - stop when n does not exist
$n = 1;
$file = $tmp . $n . ".png";
while (file_exists($file))
{
$data = file_get_contents($file);
$images = split_scanning($data);
unset($image);
unset($data);
foreach($images as $data)
{
//header Cropped Function
// Original image
$filename = $data;
// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);
// The x and y coordinates on the original image where we
// will begin cropping the image
$left = 50;
$top = 50;
// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = 200;
$crop_height = 200;
// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
$crop = imagepng($canvas, $filename, 100);
//check for header Cropped Image
what function should i made here ?
$pid = $pid.$pages;
if ($pid)
{
$pages++;
$record = defaultpage($qid,$pid,$crop);
$db->AutoExecute('pages',$record,'INSERT');
}
else
print T_("INVALID - IGNORING BLANK PAGE");
unset($data);
unset($crop);
i am confused here,that how should i check and compare if the image exists in the database or not. Please help
For cropping the image
i have found a solution
$data = '1.png';
list($current_width, $current_height) = getimagesize($data);
// The x and y co-ordinates on the original image where we will begin cropping the image
$left = 1100;
$top = 30;
// final size of image
$crop_width = 200;
$crop_height = 200;
//Resample the Image
$canvas = imagecreatefromtruecolor($crop_width, $crop_height);
$current_image = imagecreatefrompng($data);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
imagepng($canvas, $data, 100);
For comparing two images
array image_compare(mixed $image1, mixed $image2, int $RTolerance, int $GTolerance, int $BTolerance, int $WarningTolerance, int $ErrorTolerance)
Parameters
image1
- A string containing the path to the image, or a resource of an image already created by GD Library. This is the first image to be compared.
image2
- A string containing the path to the second image, or a resource of the second image already created by GD Library. This will be the second image to be compared.
RTolerance, GTolerance, BTolerance (0-255)
- Specifies the maximum deviation for the red, green, or blue (respectively) channel before throwing a flag.
WarningTolerance (0-100)
- Percentage of channel differences before warning returned.
ErrorTolerance (0-100)
- Percentage of channel differences before error (flag) returned.
Return Values
An array will be returned with the following information:
PixelsByColors
- Pixel quantity * 3 (for each of R,G, and B channels).
PixelsOutOfSpec
- (If a pixel varies outside of xTolerance, for each red, green, and blue. Where x = R/G/B) If any channel exceeds the threshhold, this number is incremented.
PercentDifference
- The percentage of difference comparing PixelsOutOfSpec to PixelsByColors
WarningLevel and ErrorLevel
- If the percentage was large enough to trigger either the specified warning, or error level.
For comparison i have to work, i am thinking to use array.Using Select query for
getting images from the database,using while loop and fetching the result in array,calling array keys for the image to be stored in variable and using if else condition in the compare function above will work i think. What you people think ?
For image comparision, No Scanned image can be 100 percent accurate, so image comparision is not so easy. It is quite hectic task.
After a Lot of Research and work, I came to a point that if it is 100 percent necessary to do image comparision. I will have to use Php-OpenCV Library. If i have to allow some sort of error tolerance, the above class can work properly. My work can was achieved using Php-tesseract. I have simply used tesseract-OCR. I used ghostscript for converting the PDF into png, cropped the image, convert that particular part of image into text using Php-tesseract OCR Library that is placed on google Code website. Called that text into variable,using regexpression i was able to check that whether a particular text exists in the variable or not and used it in the condition as requried for me.
Consider this as end of my problem.
For convenience of the visitors i am pasting my Code Snippet so that it can be used.
// Cropping the image
// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($file);
// The x and y co-ordinates on the original image where we will begin cropping the image
$left = 1100;
$top = 30;
// final size of image
$crop_width = 700;
$crop_height = 200;
//Resample the Image
$canvas = imagecreatetruecolor($crop_width,$crop_height);
$current_image = imagecreatefrompng($file);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
imagepng($canvas, $file, 1);
// Note you will have to install Php tesseract Library before making the API Call.
$api= new TessBaseAPI;
$api->Init(".","eng",$mode_or_oem=OEM_DEFAULT);
$api->SetPageSegMode(PSM_AUTO);
$mImgFile = $file;
$handle=fopen($mImgFile,"rb");
$mBuffer=fread($handle,filesize($mImgFile));
//print strlen($mBuffer);
$result=ProcessPagesBuffer($mBuffer,strlen($mBuffer)*4,$api);
//print $result;
$result = ProcessPagesFileStream($mImgFile,$api);
//print "result(ProcessPagesFileStream)=";
print $result;
$txtchk = 'FORM';
if(preg_match("/$txtchk/i", $result)) {
echo true;
}
I hope it will be helpful for lot of people.
How do I change a rectangular image to a square-shaped avatar in php, such that no matter what is the resolution of the uploaded image, it is able to resize to a centralized 42 x 42 pixel avatar. This is the php code I am using. Anyone can advise.
<?php
//Name you want to save your file as
$save = 'myfile1.jpg';
$file = 'original1.jpg';
echo "Creating file: $save";
$size = 0.45;
header('Content-type: image/jpeg') ;
list($width, $height) = getimagesize($file) ;
$modwidth = $width * $size;
$modheight = $height * $size;
$tn = imagecreatetruecolor($modwidth, $modheight) ;
$image = imagecreatefromjpeg($file) ;
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
// Here we are saving the .jpg, you can make this gif or png if you want
//the file name is set above, and the quality is set to 100%
imagejpeg($tn, $save, 100) ;
?>
First you need to be tell where is the central square in a rectangle with dimensions $x and $y.
// horizontal rectangle
if ($x > $y) {
$square = $y; // $square: square side length
$offsetX = ($x - $y) / 2; // x offset based on the rectangle
$offsetY = 0; // y offset based on the rectangle
}
// vertical rectangle
elseif ($y > $x) {
$square = $x;
$offsetX = 0;
$offsetY = ($y - $x) / 2;
}
// it's already a square
else {
$square = $x;
$offsetX = $offsetY = 0;
}
Now we can build a square from it, just need to resize it to 42x42. Something like this should work:
list($x, $y) = getimagesize($file);
// code snippet from above goes here
// so we get the square side and the offsets
$endSize = 42;
$tn = imagecreatetruecolor($endSize, $endSize);
imagecopyresampled($tn, $image, 0, 0, $offsetX, $offsetY, $endSize, $endSize, $square, $square);
So, if we have a rectangular image 100x80, the code will figure out that the big square size is 80, x offset is 10, y offset is 0. Roughly, it looks like this:
100
-----------
| |
| | 80
| |
-----------
|
V
80
--------- 42
| | -----
| | 80 ---> | | 42
| | -----
---------
After we crop the big square from the original rectangle, we just shrink it to the end size, which is 42 in your case.
Just tested and works perfectly, make sure you remove the echo line if you plan to output the image into the browser (combined with the header).
I don't know if someone was looking for this, but I needed to have a 600 x 600 squared image.
The source could be any rectangular image and I needed to mantain proportion of the original image and center the original rectangular image in a 600 x 600 squared white image.
Here it is
src_file: URL of Source Image
destination_file: Path where the destination file will be saved.
square_dimensions (pixels). I needed 600, but could be any value.
jpeg_quality: Quality (0, 100) . I used default 90
function square_thumbnail_with_proportion($src_file,$destination_file,$square_dimensions,$jpeg_quality=90)
{
// Step one: Rezise with proportion the src_file *** I found this in many places.
$src_img=imagecreatefromjpeg($src_file);
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
$ratio1=$old_x/$square_dimensions;
$ratio2=$old_y/$square_dimensions;
if($ratio1>$ratio2)
{
$thumb_w=$square_dimensions;
$thumb_h=$old_y/$ratio1;
}
else
{
$thumb_h=$square_dimensions;
$thumb_w=$old_x/$ratio2;
}
// we create a new image with the new dimmensions
$smaller_image_with_proportions=ImageCreateTrueColor($thumb_w,$thumb_h);
// resize the big image to the new created one
imagecopyresampled($smaller_image_with_proportions,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
// *** End of Step one ***
// Step Two (this is new): "Copy and Paste" the $smaller_image_with_proportions in the center of a white image of the desired square dimensions
// Create image of $square_dimensions x $square_dimensions in white color (white background)
$final_image = imagecreatetruecolor($square_dimensions, $square_dimensions);
$bg = imagecolorallocate ( $final_image, 255, 255, 255 );
imagefilledrectangle($final_image,0,0,$square_dimensions,$square_dimensions,$bg);
// need to center the small image in the squared new white image
if($thumb_w>$thumb_h)
{
// more width than height we have to center height
$dst_x=0;
$dst_y=($square_dimensions-$thumb_h)/2;
}
elseif($thumb_h>$thumb_w)
{
// more height than width we have to center width
$dst_x=($square_dimensions-$thumb_w)/2;
$dst_y=0;
}
else
{
$dst_x=0;
$dst_y=0;
}
$src_x=0; // we copy the src image complete
$src_y=0; // we copy the src image complete
$src_w=$thumb_w; // we copy the src image complete
$src_h=$thumb_h; // we copy the src image complete
$pct=100; // 100% over the white color ... here you can use transparency. 100 is no transparency.
imagecopymerge($final_image,$smaller_image_with_proportions,$dst_x,$dst_y,$src_x,$src_y,$src_w,$src_h,$pct);
imagejpeg($final_image,$destination_file,$jpeg_quality);
// destroy aux images (free memory)
imagedestroy($src_img);
imagedestroy($smaller_image_with_proportions);
imagedestroy($final_image);
}
Here is working snippet from my animal adoption project that cuts the middle of the image (horizontal or vertical) and makes it square, without adding white fields to the destination image:
/**
* Cuts a square image from the middle of rectangular image
* Requires: mbstring, exif, gd built-in extensions uncommented in php.ini
* Resamples rect img to square img and converts jpeg to wepp image
*
*/
function squarify($src_file,$dst_file,$square_side=600,$quality=90) {
// Deals only with jpeg
if(exif_imagetype($src_file) != IMAGETYPE_JPEG) { return 'src_not_jpeg'; }
// Convert old file into img
$src_img=imagecreatefromjpeg($src_file);
$src_side_x=imageSX($src_img);
$src_side_y=imageSY($src_img);
// Do not magnify image if its sides less than desired square side,
// issue false if image size is too small
// Remove, if you want src image be magnified
// if($src_side_x < $square_side || $src_side_y < $square_side) {
// return 'src_too_small';
// }
// Create new image
$dst_image=imagecreatetruecolor($square_side,$square_side);
// The image is square, just issue
// resampled image with adjusted square sides and image quality
if($src_side_x==$src_side_y) {
imagecopyresampled(
$dst_image,
$src_img,
0,
0,
0,
0,
$square_side,
$square_side,
$src_side_x,
$src_side_x
);
// The image is vertical, use x side as initial square side
} elseif($src_side_x<$src_side_y) {
$x1=0;
$y1=round(($src_side_y-$src_side_x)/2);
imagecopyresampled(
$dst_image,
$src_img,
0,
0,
$x1,
$y1,
$square_side,
$square_side,
$src_side_x,
$src_side_x
);
// The image is horizontal, use y side as initial square side
} else {
$x1=round(($src_side_x-$src_side_y)/2);
$y1=0;
imagecopyresampled(
$dst_image,
$src_img,
0,
0,
$x1,
$y1,
$square_side,
$square_side,
$src_side_y,
$src_side_y
);
}
// Save it to the filesystem
// imagewebp($dst_image,$dst_file,$quality);
// Or show it in the browser,
// dont forget about header('Content-type: image/webp')
imagewebp($dst_image,$dst_file,$quality);
}
And you can call this function on existing image:
if(!extension_loaded('mbstring')) { die('Err: mbstring extension not loaded.'); }
if(!extension_loaded('exif')) { die('Err: exif extension not loaded.'); }
if(!extension_loaded('gd')) { die('Err: gd extension not loaded.'); }
header('Content-type: image/webp');
squarify('images/src.jpg','images/res.webp',300,80);
i've tried to make a image gallery, but I'm stuck on shrinking script. I have it made as function. Original input $_FILES['image'] is substitued on $original.
I'm pretty sure this part is OK, but I'm adding it for better orientation.
$orig_udaje = getimagesize($original['tmp_name']);
$orig_sirka = $orig_udaje[0]; //original width
$orig_vyska = $orig_udaje[1]; //original height
$orig_typ = $orig_udaje[2]; //type of original image
$div_size = 150; //size of image div = size of future thumbnail's smaller side
// choosing smaller side & defining resizing scale
if ($orig_sirka>$orig_vyska)
{
$mira = $orig_vyska / $div_size;
}
else
{
$mira = $orig_sirka / $div_size;
}
$nahled_sirka = $orig_sirka / $mira;
$nahled_vyska = $orig_vyska / $mira;
I think the troubled part is somewhere below this text.
$nahled_cache = imagecreatetruecolor($nahled_sirka, $nahled_vyska);
imagecolortransparent($nahled_cache, "0, 0, 0");
if ($orig_typ == "image/jpeg")
{
$nahled_tvorba = imagecreatefromjpeg($original['tmp_name']);
imagecopyresampled($nahled_cache, $nahled_tvorba, 0, 0, 0, 0, $nahled_sirka, $nahled_vyska, $orig_sirka, $orig_vyska);
imagejpeg($nahled_cache, "/data/images/gallery/thumbs/output.jpg");
imagejpeg($original['tmp_name'], "/data/images/gallery/originals/output.jpg");
unlink($original['tmp_name']);
}
if ($orig_typ == "image/png")
{
$obrazek_tvorba = imagecreatefrompng($original['tmp_name']);
imagecopyresampled($nahled_cache, $nahled_tvorba, 0, 0, 0, 0, $nahled_sirka, $nahled_vyska, $orig_sirka, $orig_vyska);
imagepng($nahled_cache, "/data/images/gallery/thumbs/output.png");
imagepng($original['tmp_name'], "/data/images/gallery/originals/output.png");
unlink($original['tmp_name']);
}
Thank you for your advice.
I suggest you not to write the code, that already written so many times...
Try to use some open source classes. Like this one. The class is easy and lightweight, and have pretty good documentation.
The usage is simple:
// *** Include the class
include("resize-class.php");
// *** 1) Initialize / load image
$resizeObj = new resize('sample.jpg');
// *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
$resizeObj -> resizeImage(150, 100, 'crop');
// *** 3) Save image
$resizeObj -> saveImage('sample-resized.gif', 100);
You can use 'auto' option instead of 'crop', and provide max width and height. This mean's, that the image resolution will be generated based on the maximum properties you provided, and also, based on image orientation. Try it ;)
I am working on a script to crop images. It's working on jpgs. But is there a way to make it apply to various file types (bmp, png, gif) without going through various if clauses?
//create the crop
// Original image
$filename = 'uploads/'.$image_name;
$endname = 'uploads/thumbnails/'.$image_name;
// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);
// The x and y coordinates on the original image where we
// will begin cropping the image
$left = 0;
$top = 0;
// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = 200;
$crop_height = 200;
// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $crop_width, $crop_height);
imagejpeg($canvas, $endname, 100);
I tried replacing imcreatefromjpeg with imagecreate but that didn't work.
imagecreatefromstring automatically detects filetype, but it requires image data as a string, but you could always do
$current_image = imagecreatefromstring(file_get_contents($filename));
scr - for your source files
dest - for resulting files
$size = getimagesize($src);
// Detect file format from MIME-information, detected by getimagesize() function
// And select proper imagecreatefrom()-function.
$format = strtolower(substr($size['mime'], strpos($size['mime'], '/')+1));
$icfunc = "imagecreatefrom" . $format;
if (!function_exists($icfunc)){
echo "Function $icfunc doesn't exists!");
}
//Here is the magic: We call function, which name is value of variable
$isrc = $icfunc($src);
// Create new img
$idest = imagecreatetruecolor($width_dest, $height_dest);
// Copy src img to dest img with resizing
imagecopyresampled(
$idest, $isrc, // dest & src img ident
0,0, // dest img (x,y) top left corner
0,0, // src img (x,y) top left corner
$width_dest, $height_dest,
$width_src, $height_src
);