I have the following script (it looks long, but well commented). Problem is, i get errors when i try to upload a png or gif image. What can i do to adjust this (easy if possible) so that it can either work with png's and gif's or convert them before trying to work with them.
This is the error that i recieve
Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG library reports unrecoverable error
Aparently the first part of the script is working, saving the original upload, but how should i go about this?
$idir = "images/"; // Path To Images Directory
$tdir = "images/"; // Path To Thumbnails Directory
$twidth = "125"; // Maximum Width For Thumbnail Images
$theight = "100"; // Maximum Height For Thumbnail Images
$url = $_FILES['imagefile']['name']; // Set $url To Equal The Filename For Later Use
if ($_FILES['imagefile']['type'] == "image/jpg" || $_FILES['imagefile']['type'] == "image/jpeg" || $_FILES['imagefile']['type'] == "image/pjpeg" || $_FILES['imagefile']['type'] == "image/png" || $_FILES['imagefile']['type'] == "image/gif") {
$file_ext = strrchr($_FILES['imagefile']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php
$fdate = date( 'ssU' );
$copy = copy($_FILES['imagefile']['tmp_name'], "$idir" . $fdate . "$file_ext"); // Move Image From Temporary Location To Permanent Location
if ($copy) { // If The Script Was Able To Copy The Image To It's Permanent Location
print 'Image uploaded successfully.<br />'; // Was Able To Successfully Upload Image
$simg = imagecreatefromjpeg("$idir" . "$fdate" . "$file_ext"); // Make A New Temporary Image To Create The Thumbanil From
$currwidth = imagesx($simg); // Current Image Width
$currheight = imagesy($simg); // Current Image Height
if ($currheight > $currwidth) { // If Height Is Greater Than Width
$zoom = $twidth / $currheight; // Length Ratio For Width
$newheight = $theight; // Height Is Equal To Max Height
$newwidth = $currwidth * $zoom; // Creates The New Width
} else { // Otherwise, Assume Width Is Greater Than Height (Will Produce Same Result If Width Is Equal To Height)
$zoom = $twidth / $currwidth; // Length Ratio For Height
$newwidth = $twidth; // Width Is Equal To Max Width
$newheight = $currheight * $zoom; // Creates The New Height
}
$dimg = imagecreate($newwidth, $newheight); // Make New Image For Thumbnail
imagetruecolortopalette($simg, false, 256); // Create New Color Pallete
$palsize = ImageColorsTotal($simg);
for ($i = 0; $i < $palsize; $i++) { // Counting Colors In The Image
$colors = ImageColorsForIndex($simg, $i); // Number Of Colors Used
ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']); // Tell The Server What Colors This Image Will Use
}
imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight); // Copy Resized Image To The New Image (So We Can Save It)
$fdate = date( 'ssU' );
imagejpeg($dimg, "$tdir" . "thumb_" . $fdate . "$file_ext"); // Saving The Image
$full = "$fdate" . "$file_ext";
$thumb = "thumb_" . $fdate . "$file_ext";
imagedestroy($simg); // Destroying The Temporary Image
imagedestroy($dimg); // Destroying The Other Temporary Image
print 'Image thumbnail created successfully.'; // Resize successful
} else {
print '<font color="#FF0000">ERROR: Unable to upload image.</font>'; // Error Message If Upload Failed
}
} else {
print '<font color="#FF0000">ERROR: Wrong filetype (has to be a .jpg or .jpeg. Yours is '; // Error Message If Filetype Is Wrong
print $file_ext; // Show The Invalid File's Extention
print '.</font>';
}
Any guidance here is greatly appreciated.
Well, imagecreatefromjpeg() can only create images from... jpegs. There are sister functions for creating images from other file types, namely imagecreatefrompng() and imagecreatefromgif().
I've added to your code. Give it a try. Make sure you see the changes, as I put a die() in there in case of an invalid image, which may not be what you want:
$url = $_FILES['imagefile']['name']; // Set $url To Equal The Filename For Later Use
if ($_FILES['imagefile']['type'] == "image/jpg" || $_FILES['imagefile']['type'] == "image/jpeg" || $_FILES['imagefile']['type'] == "image/pjpeg" || $_FILES['imagefile']['type'] == "image/png" || $_FILES['imagefile']['type'] == "image/gif") {
$file_ext = strrchr($_FILES['imagefile']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php
$fdate = date( 'ssU' );
$copy = copy($_FILES['imagefile']['tmp_name'], "$idir" . $fdate . "$file_ext"); // Move Image From Temporary Location To Permanent Location
if ($copy) { // If The Script Was Able To Copy The Image To It's Permanent Location
print 'Image uploaded successfully.<br />'; // Was Able To Successfully Upload Image
$cfunction = 'imagecreatefromjpeg';
if ($_FILES['imagefile']['type'] == "image/png") {
$cfunction = 'imagecreatefrompng';
} else if ($_FILES['imagefile']['type'] == "image/gif") {
$cfunction = 'imagecreatefromgif';
} else {
die("Invalid image format.");
}
$simg = $cfunction("$idir" . "$fdate" . "$file_ext"); // Make A New Temporary Image To Create The Thumbanil From
$currwidth = imagesx($simg); // Current Image Width
$currheight = imagesy($simg); // Current Image Height
if ($currheight > $currwidth) { // If Height Is Greater Than Width
$zoom = $twidth / $currheight; // Length Ratio For Width
$newheight = $theight; // Height Is Equal To Max Height
$newwidth = $currwidth * $zoom; // Creates The New Width
} else { // Otherwise, Assume Width Is Greater Than Height (Will Produce Same Result If Width Is Equal To Height)
$zoom = $twidth / $currwidth; // Length Ratio For Height
$newwidth = $twidth; // Width Is Equal To Max Width
$newheight = $currheight * $zoom; // Creates The New Height
}
$dimg = imagecreate($newwidth, $newheight); // Make New Image For Thumbnail
imagetruecolortopalette($simg, false, 256); // Create New Color Pallete
$palsize = ImageColorsTotal($simg);
for ($i = 0; $i < $palsize; $i++) { // Counting Colors In The Image
$colors = ImageColorsForIndex($simg, $i); // Number Of Colors Used
ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']); // Tell The Server What Colors This Image Will Use
}
imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight); // Copy Resized Image To The New Image (So We Can Save It)
$fdate = date( 'ssU' );
imagejpeg($dimg, "$tdir" . "thumb_" . $fdate . "$file_ext"); // Saving The Image
$full = "$fdate" . "$file_ext";
$thumb = "thumb_" . $fdate . "$file_ext";
imagedestroy($simg); // Destroying The Temporary Image
imagedestroy($dimg); // Destroying The Other Temporary Image
print 'Image thumbnail created successfully.'; // Resize successful
} else {
print '<font color="#FF0000">ERROR: Unable to upload image.</font>'; // Error Message If Upload Failed
}
} else {
print '<font color="#FF0000">ERROR: Wrong filetype (has to be a .jpg or .jpeg. Yours is '; // Error Message If Filetype Is Wrong
print $file_ext; // Show The Invalid File's Extention
print '.</font>';
}
Related
Background:
I have been working on an issue whereby a file upload form will only accept certain images, it is not a problem with image size(dimensions) or with size(filesize) but I think i've found it's to do with image bit depth, as the PHP script resizes the image and applies a static (semi-transparant) watermark file to the image and saves the result.
I have gone through a long process today and yesterday working with this as the error that occurs is the server stating "Connection reset by server" . Which I think I've narrowed down to the server not having enough free memory to complete the image resource manipulations.
Issue:
Then, after all that, this error comes up on file upload submission:
IPS detected for "WEB PHP EXIF Process IFD TAG Remote Integer Overflow -2 (CVE-20/Buffer Over Flow"
Some googling only tells me that it's a securty vulnerabiliy for PHP < 4.2 or so, and doesn't relate to actually what's going on.
I have looked through my code and am very sure that
My query is to try and shed some light on what this error statement means (and how I can go about correcting it)?
Notes:
PHP 5.6.16
No PHP EXIF functions run on the page.
I can't see anywhere on the page that would cause an integer overflow (running to infinity, I guess)
Page does use imagecopy, imagealphablending and imagesavealpha But this error notice seems to appear before the script runs on the uploaded file.
This error only occurs on some uploaded images and not on others.
I have found no Apache error logs relating to this
I have no PHP errors recorded.
Code:
As I think the issue may occur somehow before the page loads I'm not sure how useful this code block will be but, take a look:
(also please note that I am aware this page is 5 years old and isn't the smartest programming, i have fixed it up in parts but am aware it can probably be further tidied)
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
///first set out variables.
$goodImage = 0;
$maxfilesize = (int)$_POST['MAX_FILE_SIZE'];
$gallery = (int)$_POST['galfolderid']
if (empty($gallery)) {
$_SESSION['message'] = $gallery . "<br/>Gallery Value has not been set.";
}
elseif (!is_numeric($gallery)) {
$_SESSION['message'] = $gallery . "<br/>Gallery Value is not a numeric value.";
}
elseif (!is_dir($_SERVER['DOCUMENT_ROOT']."/images/gallery/" . $gallery )) {
$_SESSION['message'] = $gallery . "<br/>Gallery Value, while being a number, is not a valid numeric value.";
}
if(!empty($_SESSION['message'])) {
header("Location:editgallery.php?gallery=".$galleryid);
exit;
}
for($count=0;$count<5;$count++) {
if ($_FILES['image']['error'][$count] == 0) {
clearstatcache();
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$imageType = finfo_file($finfo, $_FILES['image']['tmp_name'][$count]);
finfo_close($finfo);
unset($finfo);
if (strtolower($imageType) == "image/png") {
$imgtype = "PNG";
$original = imagecreatefrompng($_FILES['image']['tmp_name'][$count]);
} elseif (strtolower($imageType) == "image/jpeg" || strtolower($imageType) == "image/jpg") {
$imgtype = "JPG";
$original = imagecreatefromjpeg($_FILES['image']['tmp_name'][$count]);
} else {
//not a JPG or PNG type... set error.
$_SESSION['message'] = "Image " . ($count+1) . " does not appear to be a valid .JPG or .PNG file. ";
error_log($_SESSION['message']);
header("Location:editgallery.php");
exit;
}
unlink($_FILES['image']['tmp_name'][$count]);
$edgePadding = (int)$_POST['WMedge'][$count]; //integer
$watermarkScale = $_POST['WMscale'][$count]; //float
$h_position = $_POST['Hpos'][$count]; //text array
$v_position = $_POST['Vpos'][$count]; //text array
$Hoz = $h_position[0];
$Vez = $v_position[0];
if (!isset($watermarkScale) || empty($watermarkScale) || !is_numeric($watermarkScale)) {
$watermarkScale = 1.0;
}
elseif($watermarkScale > 2.0) {
$watermarkScale = 2.0;
}
elseif($watermarkScale < 0.5) {
$watermarkScale = 0.5;
}
if ((!isset($edgePadding) || empty($edgePadding) || !is_numeric($edgePadding)) && $edgePadding !== "0") {
$edgePadding = 5;
}
// be sure that the other options we need have some kind of value
if ($_FILES['image']['size'][$count] > $maxfilesize) {
$_SESSION['message'] .= "Image file ".($count+1)." appears to be too big. There is a limit of 2Mb on the
size of the image you can upload. Please click 'Back' on your browser and resubmit a valid image.";
error_log($_SESSION['message']);
//file too big.
}
//target name is the number of images in the LARGE gallery,
///cycle through imagenames to find the first "clear" image number.
$newimagename = 1;
clearstatcache();
/***
NOTE: Only possible place an integer oveflow might occur I think
***/
while (file_exists($_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $gallery . "/S/" . $newimagename . ".jpg")) {
$newimagename++;
}
///newimagename is the new filename of the image.
$target_name = $newimagename . ".jpg";
$target = $_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $gallery . "/L/" . $target_name;
$targetSmall = $_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $gallery . "/S/" . $target_name;
//targetSM is used below to make the thumbnail image. for the SMALL gallery.
//full target directory and name.
// file upload success
// now file need resizing before the watermark is applied.
// resize new dimensions (Large- 800px)
$originalImageSize[0] = imagesx($original);
$originalImageSize[1] = imagesy($original);
/***
* Resize new dimensions for small thumbnail.
***/
if ($originalImageSize[0] > 133) {
$percent = 133 / $originalImageSize[0];
} else {
$percent = 1;
}
$newThumbHeight = $originalImageSize[1] * $percent;
$newThumbWidth = $originalImageSize[0] * $percent;
// Resample
$imageThumbFinal = imagecreatetruecolor($newThumbWidth, $newThumbHeight);
imagecopyresampled($imageThumbFinal, $original, 0, 0, 0, 0, $newThumbWidth, $newThumbHeight, $originalImageSize[0], $originalImageSize[1]);
// Output
imagejpeg($imageThumbFinal, $targetSmall, 80);
imagedestroy($imageThumbFinal);
unset($imageThumbFinal, $percent,$newThumbWidth,$newThumbHeight);
/***
* End Thumbnail generation.
*/
/***
* Resize main sized image (max 800px wide)
***/
if ($originalImageSize[0] > 800) {
$percent = 800 / $originalImageSize[0];
} else {
$percent = 1;
}
$newPictureHeight = $originalImageSize[1] * $percent;
$newPictureWidth = $originalImageSize[0] * $percent;
// Resample main image to reduce max size.
$imageCleanFinal = imagecreatetruecolor($newPictureWidth, $newPictureHeight);
imagecopyresampled($imageCleanFinal, $original, 0, 0, 0, 0, $newPictureWidth, $newPictureHeight, $originalImageSize[0], $originalImageSize[1]);
/***
* Now resize the watermark and save onto the final image.
***/
//full target directory and name.
$watermark = $_SERVER['DOCUMENT_ROOT'] . "/images/watermark2.png";
$wmTarget = substr($watermark, 0, -3) . "tmp"; //image/watermark2.tmp is resized.
$sourceWaterImage = imagecreatefrompng($watermark);
$waterMarkWidth = imagesx($sourceWaterImage);
$waterMarkHeight = imagesy($sourceWaterImage);
$destinationHeight = $waterMarkHeight * $watermarkScale;
$destinationWidth = $waterMarkWidth * $watermarkScale;
$destinationHeight = floor($destinationHeight);
$destinationWidth = floor($destinationWidth);
$destinationWatermarkImage = imagecreatetruecolor($destinationWidth, $destinationHeight);
imagealphablending($destinationWatermarkImage, FALSE);
imagesavealpha($destinationWatermarkImage, TRUE);
imagecopyresampled($destinationWatermarkImage, $sourceWaterImage, 0, 0, 0, 0, $destinationWidth,
$destinationHeight, $waterMarkWidth, $waterMarkHeight);
imagedestroy($sourceWaterImage);
unset($sourceWaterImage);
clearstatcache();
/***
* Set watermark location on final image.
***/
$differenceX = $newPictureWidth - $destinationWidth;
$differenceY = $newPictureHeight - $destinationHeight;
switch ($Hoz) {
// find the X coord for placement
case 'left':
$placementX = $edgePadding;
break;
case 'center':
$placementX = round($differenceX / 2);
break;
case 'right':
$placementX = $newPictureWidth - ($destinationWidth + $edgePadding);
break;
default:
$placementX = 0;
break;
}
switch ($Vez) {
// find the Y coord for placement
case 'top':
$placementY = $edgePadding;
break;
case 'middle':
$placementY = round($differenceY / 2);
break;
case 'bottom':
$placementY = $newPictureHeight - ($destinationHeight + $edgePadding);
break;
default:
$placementY = 0;
break;
}
/***
* Finish set Watermark location
***/
imagecopy($imageCleanFinal,
$destinationWatermarkImage,
$placementX,
$placementY,
0,
0,
$destinationWidth,
$destinationHeight);
imagejpeg($imageCleanFinal, $target, 80);
/***
* Image final save
***/
// Output
imagejpeg($imageCleanFinal, $target, 80);
imagedestroy($imageCleanFinal);
imagedestroy($destinationWatermarkImage);
unset($imageCleanFinal, $percent);
unlink($wmTarget);
$output[$goodImage]['targetName'] = $target_name;
$output[$goodImage]['targetAddr'] = $target;
$goodImage++;
} elseif (!isset($_FILES['image']['name'][$count]) || ($_FILES['image']['error'][$count] != 0 && $_FILES['image']['error'][$count] != 4)) {
//error in file upload.
$_SESSION['message'] .= " There is a file upload error number " . $_FILES['image']['error'][$count] . ". for image ".($count+1).".
Please try resubmitting a valid image.";
error_log($_SESSION['message']);
}
}
if (empty($_SESSION['message'])){
$_SESSION['message'] = $goodImage." New Image(s) Uploaded";
}
// display resulting image for download
header("Location:editgallery.php?special=yes&gallery=".$galleryid);
exit;
Server Details:
Apache 2.4
WebHostManger & CPanel (combined) version 54.0.19
PHP 5.6 using Mod suPHP 0.7.2
2 core 2.2GHz (so x2) intel with
1896Mb/2097Mb physical memory (used/available)
+4095Mb memory Swap File. (~6010Mb total)
How can i resize proportionaly image in php without "squishing" ? I need some solution, i was searching here, but i could't find anything what i need.
What i have:
<?php
if (isset($_SESSION['username'])) {
if (isset($_POST['upload'])) {
$allowed_filetypes = array('.jpg', '.jpeg', '.png', '.gif');
$max_filesize = 10485760;
$upload_path = 'gallery/';
$filename = $_FILES['userfile']['name'];
$ext = substr($filename, strpos($filename, '.'), strlen($filename) - 1);
if (!in_array($ext, $allowed_filetypes)) {
die('The file you attempted to upload is not allowed.');
}
if (filesize($_FILES['userfile']['tmp_name']) > $max_filesize) {
die('The file you attempted to upload is too large.');
}
if (!is_writable($upload_path)) {
die('You cannot upload to the specified directory, please CHMOD it to 777.');
}
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path.$filename)) {
$q = mysqli_query($connection, "UPDATE users SET avatar='".$_FILES['userfile']['name']."' WHERE username ='".$_SESSION['username']."'");
echo "<font color='#5cb85c'>Браво, успешно си качил/а профилна снимка!</font>";
} else {
echo 'There was an error during the file upload. Please try again.';
}
}
echo ' <form action="images.php" method="post" enctype="multipart/form-data"> ';
echo ' <input type="file" name="userfile"/>';
echo ' <input type="submit" name="upload" value="Качи">';
echo ' </form>';
} else {
echo "<font color='#ec3f8c'>Съжелявам! За да качиш снимка във профила си, <a href='login.php'><font color='#ec3f8c'><b> трябва да се логнеш</b> </font></a></font>";
}
?>
I want to add something like this:Click here
how i call images?
echo '<a href="profiles.php?id='.$rowtwo['id'].'">';
echo"<img src='gallery/".$rowtwo['avatar']."' width='170px' height='217px'/>";
echo'</a>';
I save my image of avatar in DB in users as avatar.
It's much easier to use JS. It also works better because you're letting the client do the slow work of manipulation vs using your finite server resources for that task.
Here's a sample:
//This is the URL to your original image
var linkUrl = "http://www.mywebsite.com/myimage.png";
//This is a div that is necessary to trick JS into letting you manipulate sizing
//Just make sure it exists and is hidden
var img = $('#HiddenDivForImg');
//This is a call to the function
image_GetResizedImage(img, linkUrl);
//This function does the magic
function image_GetResizedImage(img, linkUrl) {
//Set your max height or width dimension (either, not both)
var maxDim = 330;
//Define the equalizer to 1 to avoid errors if incorrect URL is given
var dimEq = 1;
//This determines if the larger dimension is the images height or width.
//Then, it divides that dimension by the maxDim to get a decimal number for size reduction
if (img.height() > maxDim || img.width() > maxDim) {
if (img.height() > img.width()) {
dimEq = maxDim / img.height();
} else {
dimEq = maxDim / img.width();
}
}
var imageOutput = "<a href='" + linkUrl + "' target='_blank'>View Larger</a><br /><a href='" + result +
"' target='_blank'><img src='" + linkUrl + "' style='width: " + img.width() * dimEq
+ "px; height: " + img.height() * dimEq + "px' /></a>";
//This returns a URL for the image with height and width tags of the resized (non-squished) image.
return imageOutput;
}
For image manipulation in PHP you can use Imagemagick.
http://www.imagemagick.org/
It's the scale command you are looking for.
Here I have created a function with your reference link, you can use it like this
Call it
//Resize uploaded image
resize_image($_FILES['userfile'], 100, 200);
//Or if you want to save image with diffrent name
$filename = $upload_path.$_SESSION['username'].'-avatar.jpg';
resize_image($_FILES['userfile'], 100, 200, $newfilename);
//if (move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path.$filename)) {
$q = mysqli_query($connection, "UPDATE users SET avatar='".$filename."' WHERE username ='".$_SESSION['username']."'");
echo "<font color='#5cb85c'>Браво, успешно си качил/а профилна снимка!</font>";
} else {
echo 'There was an error during the file upload. Please try again.';
}
Function
function resize_image($image_src, $w = 100, $h = 100, $save_as = null) {
// Create image from file
switch(strtolower($image_src['type']))
{
case 'image/jpeg':
$image = imagecreatefromjpeg($image_src['tmp_name']);
break;
case 'image/png':
$image = imagecreatefrompng($image_src['tmp_name']);
break;
case 'image/gif':
$image = imagecreatefromgif($image_src['tmp_name']);
break;
default:
exit('Unsupported type: '.$image_src['type']);
}
// Target dimensions
$max_width = $w;
$max_height = $h;
// 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);
if($save_as) {
//Save as new file
imagejpeg($new, $save_as, 90);
}else{
//Overwrite image
imagejpeg($new, $image_src['tmp_name'], 90);
}
// Destroy resources
imagedestroy($image);
imagedestroy($new);
}
I use http://image.intervention.io/. You can scale, cache, store, convert and do various image manipulation tasks.
Very easy to use.
// load the image
$img = Image::make('public/foo.jpg');
// resize the width of the image to 300 pixels and constrain proportions.
$img->resize(300, null, true);
// save file as png with 60% quality
$img->save('public/bar.png', 60);
This script will load an image (jpg, gif or png) and then save a PNG local copy for caching.
I'm trying to find a way to resize the image to 300x300 before saving it as a PNG.
I tried to use the function imagecopyresampled() but the image is still not resized.
2 problems now :
The script saves a resized PNG image in the correct folder, but the image is empty (it's all black)
The first time i will load the image, i will get an error (image cannot be displayed because it contains error) but the image will still be saved as PNG in the cache folder. Second time i load the image, it will be displayed correctly (using the cached version) but it isn't resized.
Here's the full code of my page. The first part is used to cache the image, the second part is used to display the non-cached image (it reads an image from a ZIP file and output the content without extracting anything)
if (empty($_GET['display'])) {
header('Content-Type: image/png');
$imgpochette = $_GET['i'];
$ENABLE_CACHE = true;
$CACHE_TIME_HOURS = 744;
$CACHE_FILE_PATH = "pochette_album/$imgpochette.png";
if($ENABLE_CACHE && file_exists($CACHE_FILE_PATH) && (time() - filemtime($CACHE_FILE_PATH) < ($CACHE_TIME_HOURS * 60 * 60))) {
echo #file_get_contents($CACHE_FILE_PATH);
} else {
// Load the requested image
$imgdisplay = "http://www.pirate-punk.com/pochette.php?i=$imgpochette&display=1";
$image = imagecreatefromstring(file_get_contents($imgdisplay));
$width = "30";
$height = "30";
list($originalWidth, $originalHeight) = getimagesize($CACHE_FILE_PATH);
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $width, $height, $originalWidth, $originalHeight);
// Send the image
imagepng($new_image, $CACHE_FILE_PATH);
exit();
#file_put_contents($CACHE_FILE_PATH, $output);
echo $output;
}
}
if (!empty($_GET['display'])) {
function showimage($zip_file, $file_name) {
$z = new ZipArchive();
if ($z->open($zip_file) !== true) {
echo "File not found.";
return false;
}
$stat = $z->statName($file_name);
$fp = $z->getStream($file_name);
// search for a path/to/file matching file, returning the index of it
$index = $z->locateName($file_name, ZipArchive::FL_NOCASE|ZipArchive::FL_NODIR);
// get the name of the file based on the index
$full_file_name = $z->getNameIndex($index);
// now get the stream
$fp = $z->getStream($full_file_name);
if(!$fp) {
echo "Could not load image.";
return false;
}
header('Content-Type: image/jpeg');
header('Content-Length: ' . $stat['size']);
fpassthru($fp);
return true;
}
$imgsrcencoded = $_GET['i'];
$imagesrc = base64_decode($imgsrcencoded);
$explodez = explode("#",$imagesrc);
$imgg = utf8_encode($explodez[1]);
$dirnfile = $explodez[0];
$zipp = end((explode('/', $dirnfile)));
$dirr = str_replace($zipp,"",$dirnfile);
$dirr = rtrim($dirr,"/");
$imgg = rtrim($imgg);
chdir($dirr);
if (empty($_GET['debug'])) {
echo showimage($zipp,$imgg);
}
}
Get the solution for .png images
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php resizing image on upload rotates the image when i don't want it to
I have created my first ever upload code and was testing it, the image resizes and uploads fine. The only issue I have is that it rotates.
Here is the code:
$errors = array();
$message = "";
if(isset($_POST["test"])){
$name = rand(1,999999) . $_FILES["uploadfile"]["name"];
$temp_name = $_FILES["uploadfile"]["tmp_name"];
$size = $_FILES["uploadfile"]["size"];
$extension = strtolower(end(explode('.', $_FILES['uploadfile']['name'])));
$path = "testupload/" . $name;
$info = getimagesize($temp_name);
$originalwidth = $info[0];
$originalheight = $info[1];
$mime = $info["mime"];
$acceptedHeight = 750;
$acceptedWidth = 0;
$acceptedMimes = array('image/jpeg','image/png','image/gif');
$acceptedfileSize = 4102314;
$acceptedExtensions = array('jpg','jpeg','gif','png');
echo $size;
// check mimetype
if(!in_array($mime, $acceptedMimes)){$errors[] = "mime type not allowed - The file you have just uploaded was a: " . $extension . " file!";}
if(!$errors){if($size > $acceptedfileSize){$errors[] = "filesize is to big - Your file size of this file is: " . $size;}}
if(!$errors){if(!in_array($extension, $acceptedExtensions)){$errors[] = "File extension not allowed - The file you have just uploaded was a: " . $extension . " file!";}}
if(!$errors){
// create the image from the temp file.
if ($extension === 'png'){
$orig = imagecreatefrompng($temp_name);
}elseif ($extension === 'jpeg'){
$orig = imagecreatefromjpeg($temp_name);
}elseif ($extension === 'jpg'){
$orig = imagecreatefromjpeg($temp_name);
}elseif ($extension === 'gif'){
$orig = imagecreatefromgif($temp_name);
}
// work out the new dimensions.
if ($acceptedHeight === 0){
$newWidth = $acceptedWidth;
$newHeight = ($originalheight / $originalwidth) * $acceptedWidth;
}else if ($acceptedWidth === 0){
$newWidth = ($originalwidth / $originalheight) * $acceptedHeight;
$newHeight = $acceptedHeight;
}else{
$newWidth = $acceptedWidth;
$newHeight = $acceptedHeight;
}
$originalwidth = imagesx($orig);
$originalheight = imagesy($orig);
// make ssure they are valid.
if ($newWidth < 1){ $newWidth = 1; }else{ $newWidth = round($newWidth ); }
if ($newHeight < 1){ $newHeight = 1; }else{ $newHeight = round($newHeight); }
// don't bother copying the image if its alreay the right size.
if ($originalwidth!== $newWidth || $originalheight !== $newHeight){
// create a new image and copy the origional on to it at the new size.
$new = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($new, $orig, 0,0,0,0, $newWidth, $newHeight, $originalwidth, $originalheight);
}else{
// phps copy on write means this won't cause any harm.
$new = $orig;
}
// save the image.
if ($extension === 'jpeg' || $extension === 'jpg'){
imagejpeg($new, $path, 100);
}else if ($save_ext === 'gif'){
imagegif($new, $path);
}else{
imagepng($new, $path, round(9 - (100 / (100 / 9))));
}
$message = $path;
Can someone please let me know what is going on?
Check the original image is actually in the orientation you expect. I work with images all day and the majority of the time it's Windows Photo Viewer showing the image in a certain orientation (reading an orientation change in the EXIF) but if you open it up in Photoshop it's different.
I tested your code with two images: one was landscape (width > height), the other was portrait (height > width). The code works.
The problem seems to be what #Tavocado said: newer cameras have a sensor to detect the orientation of the camera when the photo was taken, and they store that info in the photo. Also, newer photo viewing software reads that info back from the photo and rotates it before displaying the image. So you all the time see the image with the right orientation (sky up, earth down). However PHP functions (and the rest of the world) don't use that information and display the image as is was taken. That means that you will have to rotate yourself portrait images.
Just load your images in the browser (drag the file on the address bar) you you will see how the image is really stored in the file, without any automatic rotation.
The problem is that the image has embedded EXIF data, probably from the device that took the photo.
Investigate whether your images have embedded rotation information, using exif_read_data, and then auto-correct the rotation with a function like this.
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I've used this code for a while now for a few sites I've built which is great for galleries but it uses up a lot of memory and I keep getting memory allocation errors within the error log. Is there anything that can be changed to make this script better?
<?php
// Smart Image Resizer 1.4.1
// Resizes images, intelligently sharpens, crops based on width:height ratios, color fills
// transparent GIFs and PNGs, and caches variations for optimal performance
// Created by: Joe Lencioni (http://shiftingpixel.com)
// Date: August 6, 2008
// Based on: http://veryraw.com/history/2005/03/image-resizing-with-php/
/////////////////////
// LICENSE
/////////////////////
// I love to hear when my work is being used, so if you decide to use this, feel encouraged
// to send me an email. Smart Image Resizer is released under a Creative Commons
// Attribution-Share Alike 3.0 United States license
// (http://creativecommons.org/licenses/by-sa/3.0/us/). All I ask is that you include a link
// back to Shifting Pixel (either this page or shiftingpixel.com), but don’t worry about
// including a big link on each page if you don’t want to–one will do just nicely. Feel
// free to contact me to discuss any specifics (joe#shiftingpixel.com).
/////////////////////
// REQUIREMENTS
/////////////////////
// PHP and GD
/////////////////////
// PARAMETERS
/////////////////////
// Parameters need to be passed in through the URL's query string:
// image absolute path of local image starting with "/" (e.g. /images/toast.jpg)
// width maximum width of final image in pixels (e.g. 700)
// height maximum height of final image in pixels (e.g. 700)
// color (optional) background hex color for filling transparent PNGs (e.g. 900 or 16a942)
// cropratio (optional) ratio of width to height to crop final image (e.g. 1:1 or 3:2)
// nocache (optional) does not read image from the cache
// quality (optional, 0-100, default: 90) quality of output image
/////////////////////
// EXAMPLES
/////////////////////
// Resizing a JPEG:
// <img src="/image.php/image-name.jpg?width=100&height=100&image=/path/to/image.jpg" alt="Don't forget your alt text" />
// Resizing and cropping a JPEG into a square:
// <img src="/image.php/image-name.jpg?width=100&height=100&cropratio=1:1&image=/path/to/image.jpg" alt="Don't forget your alt text" />
// Matting a PNG with #990000:
// <img src="/image.php/image-name.png?color=900&image=/path/to/image.png" alt="Don't forget your alt text" />
/////////////////////
// CODE STARTS HERE
/////////////////////
if (!isset($_GET['image']))
{
header('HTTP/1.1 400 Bad Request');
echo 'Error: no image was specified';
exit();
}
define('MEMORY_TO_ALLOCATE', '100M');
define('DEFAULT_QUALITY', 90);
define('CURRENT_DIR', dirname(__FILE__));
define('CACHE_DIR_NAME', '/imagecache/');
define('CACHE_DIR', CURRENT_DIR . CACHE_DIR_NAME);
define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT']);
// Images must be local files, so for convenience we strip the domain if it's there
$image = preg_replace('/^(s?f|ht)tps?:\/\/[^\/]+/i', '', (string) $_GET['image']);
// For security, directories cannot contain ':', images cannot contain '..' or '<', and
// images must start with '/'
if ($image{0} != '/' || strpos(dirname($image), ':') || preg_match('/(\.\.|<|>)/', $image))
{
header('HTTP/1.1 400 Bad Request');
echo 'Error: malformed image path. Image paths must begin with \'/\'';
exit();
}
// If the image doesn't exist, or we haven't been told what it is, there's nothing
// that we can do
if (!$image)
{
header('HTTP/1.1 400 Bad Request');
echo 'Error: no image was specified';
exit();
}
// Strip the possible trailing slash off the document root
$docRoot = preg_replace('/\/$/', '', DOCUMENT_ROOT);
if (!file_exists($docRoot . $image))
{
header('HTTP/1.1 404 Not Found');
echo 'Error: image does not exist: ' . $docRoot . $image;
exit();
}
// Get the size and MIME type of the requested image
$size = GetImageSize($docRoot . $image);
$mime = $size['mime'];
// Make sure that the requested file is actually an image
if (substr($mime, 0, 6) != 'image/')
{
header('HTTP/1.1 400 Bad Request');
echo 'Error: requested file is not an accepted type: ' . $docRoot . $image;
exit();
}
$width = $size[0];
$height = $size[1];
$maxWidth = (isset($_GET['width'])) ? (int) $_GET['width'] : 0;
$maxHeight = (isset($_GET['height'])) ? (int) $_GET['height'] : 0;
if (isset($_GET['color']))
$color = preg_replace('/[^0-9a-fA-F]/', '', (string) $_GET['color']);
else
$color = FALSE;
// If either a max width or max height are not specified, we default to something
// large so the unspecified dimension isn't a constraint on our resized image.
// If neither are specified but the color is, we aren't going to be resizing at
// all, just coloring.
if (!$maxWidth && $maxHeight)
{
$maxWidth = 99999999999999;
}
elseif ($maxWidth && !$maxHeight)
{
$maxHeight = 99999999999999;
}
elseif ($color && !$maxWidth && !$maxHeight)
{
$maxWidth = $width;
$maxHeight = $height;
}
// If we don't have a max width or max height, OR the image is smaller than both
// we do not want to resize it, so we simply output the original image and exit
if ((!$maxWidth && !$maxHeight) || (!$color && $maxWidth >= $width && $maxHeight >= $height))
{
$data = file_get_contents($docRoot . '/' . $image);
$lastModifiedString = gmdate('D, d M Y H:i:s', filemtime($docRoot . '/' . $image)) . ' GMT';
$etag = md5($data);
doConditionalGet($etag, $lastModifiedString);
header("Content-type: $mime");
header('Content-Length: ' . strlen($data));
echo $data;
exit();
}
// Ratio cropping
$offsetX = 0;
$offsetY = 0;
if (isset($_GET['cropratio']))
{
$cropRatio = explode(':', (string) $_GET['cropratio']);
if (count($cropRatio) == 2)
{
$ratioComputed = $width / $height;
$cropRatioComputed = (float) $cropRatio[0] / (float) $cropRatio[1];
if ($ratioComputed < $cropRatioComputed)
{ // Image is too tall so we will crop the top and bottom
$origHeight = $height;
$height = $width / $cropRatioComputed;
$offsetY = ($origHeight - $height) / 2;
}
else if ($ratioComputed > $cropRatioComputed)
{ // Image is too wide so we will crop off the left and right sides
$origWidth = $width;
$width = $height * $cropRatioComputed;
$offsetX = ($origWidth - $width) / 2;
}
}
}
// Setting up the ratios needed for resizing. We will compare these below to determine how to
// resize the image (based on height or based on width)
$xRatio = $maxWidth / $width;
$yRatio = $maxHeight / $height;
if ($xRatio * $height < $maxHeight)
{ // Resize the image based on width
$tnHeight = ceil($xRatio * $height);
$tnWidth = $maxWidth;
}
else // Resize the image based on height
{
$tnWidth = ceil($yRatio * $width);
$tnHeight = $maxHeight;
}
// Determine the quality of the output image
$quality = (isset($_GET['quality'])) ? (int) $_GET['quality'] : DEFAULT_QUALITY;
// Before we actually do any crazy resizing of the image, we want to make sure that we
// haven't already done this one at these dimensions. To the cache!
// Note, cache must be world-readable
// We store our cached image filenames as a hash of the dimensions and the original filename
$resizedImageSource = $tnWidth . 'x' . $tnHeight . 'x' . $quality;
if ($color)
$resizedImageSource .= 'x' . $color;
if (isset($_GET['cropratio']))
$resizedImageSource .= 'x' . (string) $_GET['cropratio'];
$resizedImageSource .= '-' . $image;
$resizedImage = md5($resizedImageSource);
$resized = CACHE_DIR . $resizedImage;
// Check the modified times of the cached file and the original file.
// If the original file is older than the cached file, then we simply serve up the cached file
if (!isset($_GET['nocache']) && file_exists($resized))
{
$imageModified = filemtime($docRoot . $image);
$thumbModified = filemtime($resized);
if($imageModified < $thumbModified) {
$data = file_get_contents($resized);
$lastModifiedString = gmdate('D, d M Y H:i:s', $thumbModified) . ' GMT';
$etag = md5($data);
doConditionalGet($etag, $lastModifiedString);
header("Content-type: $mime");
header('Content-Length: ' . strlen($data));
echo $data;
exit();
}
}
// We don't want to run out of memory
ini_set('memory_limit', MEMORY_TO_ALLOCATE);
// Set up a blank canvas for our resized image (destination)
$dst = imagecreatetruecolor($tnWidth, $tnHeight);
// Set up the appropriate image handling functions based on the original image's mime type
switch ($size['mime'])
{
case 'image/gif':
// We will be converting GIFs to PNGs to avoid transparency issues when resizing GIFs
// This is maybe not the ideal solution, but IE6 can suck it
$creationFunction = 'ImageCreateFromGif';
$outputFunction = 'ImagePng';
$mime = 'image/png'; // We need to convert GIFs to PNGs
$doSharpen = FALSE;
$quality = round(10 - ($quality / 10)); // We are converting the GIF to a PNG and PNG needs a compression level of 0 (no compression) through 9
break;
case 'image/x-png':
case 'image/png':
$creationFunction = 'ImageCreateFromPng';
$outputFunction = 'ImagePng';
$doSharpen = FALSE;
$quality = round(10 - ($quality / 10)); // PNG needs a compression level of 0 (no compression) through 9
break;
default:
$creationFunction = 'ImageCreateFromJpeg';
$outputFunction = 'ImageJpeg';
$doSharpen = TRUE;
break;
}
// Read in the original image
$src = $creationFunction($docRoot . $image);
if (in_array($size['mime'], array('image/gif', 'image/png')))
{
if (!$color)
{
// If this is a GIF or a PNG, we need to set up transparency
imagealphablending($dst, false);
imagesavealpha($dst, true);
}
else
{
// Fill the background with the specified color for matting purposes
if ($color[0] == '#')
$color = substr($color, 1);
$background = FALSE;
if (strlen($color) == 6)
$background = imagecolorallocate($dst, hexdec($color[0].$color[1]), hexdec($color[2].$color[3]), hexdec($color[4].$color[5]));
else if (strlen($color) == 3)
$background = imagecolorallocate($dst, hexdec($color[0].$color[0]), hexdec($color[1].$color[1]), hexdec($color[2].$color[2]));
if ($background)
imagefill($dst, 0, 0, $background);
}
}
// Resample the original image into the resized canvas we set up earlier
ImageCopyResampled($dst, $src, 0, 0, $offsetX, $offsetY, $tnWidth, $tnHeight, $width, $height);
if ($doSharpen)
{
// Sharpen the image based on two things:
// (1) the difference between the original size and the final size
// (2) the final size
$sharpness = findSharp($width, $tnWidth);
$sharpenMatrix = array(
array(-1, -2, -1),
array(-2, $sharpness + 12, -2),
array(-1, -2, -1)
);
$divisor = $sharpness;
$offset = 0;
imageconvolution($dst, $sharpenMatrix, $divisor, $offset);
}
// Make sure the cache exists. If it doesn't, then create it
if (!file_exists(CACHE_DIR))
mkdir(CACHE_DIR, 0755);
// Make sure we can read and write the cache directory
if (!is_readable(CACHE_DIR))
{
header('HTTP/1.1 500 Internal Server Error');
echo 'Error: the cache directory is not readable';
exit();
}
else if (!is_writable(CACHE_DIR))
{
header('HTTP/1.1 500 Internal Server Error');
echo 'Error: the cache directory is not writable';
exit();
}
// Write the resized image to the cache
$outputFunction($dst, $resized, $quality);
// Put the data of the resized image into a variable
ob_start();
$outputFunction($dst, null, $quality);
$data = ob_get_contents();
ob_end_clean();
// Clean up the memory
ImageDestroy($src);
ImageDestroy($dst);
// See if the browser already has the image
$lastModifiedString = gmdate('D, d M Y H:i:s', filemtime($resized)) . ' GMT';
$etag = md5($data);
doConditionalGet($etag, $lastModifiedString);
// Send the image to the browser with some delicious headers
header("Content-type: $mime");
header('Content-Length: ' . strlen($data));
echo $data;
function findSharp($orig, $final) // function from Ryan Rud (http://adryrun.com)
{
$final = $final * (750.0 / $orig);
$a = 52;
$b = -0.27810650887573124;
$c = .00047337278106508946;
$result = $a + $b * $final + $c * $final * $final;
return max(round($result), 0);
} // findSharp()
function doConditionalGet($etag, $lastModified)
{
header("Last-Modified: $lastModified");
header("ETag: \"{$etag}\"");
$if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ?
stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) :
false;
$if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ?
stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']) :
false;
if (!$if_modified_since && !$if_none_match)
return;
if ($if_none_match && $if_none_match != $etag && $if_none_match != '"' . $etag . '"')
return; // etag is there but doesn't match
if ($if_modified_since && $if_modified_since != $lastModified)
return; // if-modified-since is there but doesn't match
// Nothing has changed since their last request - serve a 304 and exit
header('HTTP/1.1 304 Not Modified');
exit();
} // doConditionalGet()
// old pond
// a frog jumps
// the sound of water
// —Matsuo Basho
?>
If your server has imagemagick installed, it can be done like this:
exec("convert $filename -quality 60 -resize x100 -gravity center -crop 100x100+0+0 +repage $newfilename");
else:
Resize & Crop with GD2
Hope it helps
Yes, you can switch to using the IMagick extension, which is much better at memory handling. As I've described in an old question, GD uses memory proportional to the image size and holds it in memory entirely uncompressed.