/    Sign up×
Community /Pin to ProfileBookmark

Image resize failed?

Ok so I have a function to resize images when I upload, its called twice once for the thumbnail once for a full size. I’ve used my uploading a number of times so far and its always worked perfectly but now I’m having a problem. When I upload a square image, it works for the thumbnail but not the full size. Anyway here’s what I got, maybe I missed something…

[code=php]
function imageResize($src,$target,$newWidth,$newHeight) {
// $src = original file
// $target = new file
// $newWidth / $newHeight represent maximum dimensions
list($origWidth,$origHeight) = getimagesize($src); // Get original dimensions
if( $origWidth > $origHeight ) { // set new width/height to maintain aspect ratio
$newHeight = ($newWidth/$origWidth)*$origHeight;
} else {
$newWidth = ($newHeight/$origHeight)*$origWidth;
}
if( $origHeight < $newHeight && $origWidth < $newWidth) {
$newHeight = $origHeight;
$newWidth = $origWidth;
}
$base = imagecreatefromjpeg($src); // open source
$temp = imagecreatetruecolor($newWidth,$newHeight); //create new file
imagecopyresampled($temp,$base,0,0,0,0,$newWidth,$newHeight,$origWidth,$origHeight); // resample source into new file
if ( imagejpeg($temp,$target) ) { // copy new file to target location, if successful return true otherwise return false.
return TRUE;
} else {
return FALSE;
}
}

// upload script calling it
$tnfile = “{$uploaddir}{$filename}.{$ext}”;
$viewfile = “{$uploaddir}{$filename}_1.{$ext}”;
$error = 0;
if( imageResize($pics,$tnfile,”200″,”133″) ) {
$content .= “Thumbnail successful.<br />”;
} else {
$content .= “Thumbnail failed.<br />”;
$error++;
}
if( imageResize($pics,$viewfile,”640″,”800″) ) {
$content .= “View file successful.<br />”;
} else {
$content .= “View file failed.<br />”;
$error++;
}[/code]

Like I said it worked on the thumbnail, so I’m lost i thought maybe because it was square but then why would it still work for the thumbnail? Also there is quite a bit more to upload part, if you feel I should post that too let me know.

As always, thanks in advance! <3

to post a comment
PHP

13 Comments(s)

Copy linkTweet thisAlerts:
@NogDogMar 31.2011 — Just a guess, I didn't work it through completely, but I suspect this:
[code=php]
if( $origHeight < $newHeight && $origWidth < $newWidth) {
[/code]

...should maybe be this?
[code=php]
if( $origHeight <= $newHeight && $origWidth <= $newWidth) {
[/code]
Copy linkTweet thisAlerts:
@DerokorianauthorMar 31.2011 — Hmmm... possibly, but that still wouldn't explain why I found the problem to begin... let me look change that see if it works. (altho it shouldn't the image I found the problem on was way higher than the set newheight/width (before calc))
Copy linkTweet thisAlerts:
@DerokorianauthorMar 31.2011 — Also if only one is equal then the previous if will correct the size (supposedly) and if they are both equal it doesn't need resized anyway...
Copy linkTweet thisAlerts:
@DerokorianauthorMar 31.2011 — Nope still not resizing it...

sorry for so many posts so fast lol
Copy linkTweet thisAlerts:
@NogDogMar 31.2011 — I threw your function into a little test script and it seemed to work just fine, converting a 300x300 image to 200x200.
[code=php]
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$file1 = tempnam('.', 'img_');
$file2 = tempnam('.', 'img_');
// Create a 300x300 image
$im = imagecreate(300, 300);
// Set the background to be blue
imagecolorallocate($im, 0, 0, 200);
// Output the image to file
imagejpeg($im, $file1, 100);
imagedestroy($im);
if(imageResize($file1, $file2, 200, 200)) {
header('Content-Type: image/jpeg');
readfile($file2);
}
else {
user_error("function returned false");
}
unlink($file1);
unlink($file2);
function imageResize($src, $target, $newWidth, $newHeight)
{
// $src = original file
// $target = new file
// $newWidth / $newHeight represent maximum dimensions
list($origWidth, $origHeight) = getimagesize($src); // Get original dimensions
if ($origWidth > $origHeight) { // set new width/height to maintain aspect ratio
$newHeight = ($newWidth / $origWidth) * $origHeight;
} else {
$newWidth = ($newHeight / $origHeight) * $origWidth;
}
if ($origHeight < $newHeight && $origWidth < $newWidth) {
$newHeight = $origHeight;
$newWidth = $origWidth;
}
$base = imagecreatefromjpeg($src); // open source
$temp = imagecreatetruecolor($newWidth, $newHeight); //create new file
imagecopyresampled($temp, $base, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight); // resample source into new file
if (imagejpeg($temp, $target)) { // copy new file to target location, if successful return true otherwise return false.
return TRUE;
} else {
return FALSE;
}
}
[/code]
Copy linkTweet thisAlerts:
@DerokorianauthorMar 31.2011 — Its not returning FALSE, its returning TRUE and not resizing the picture. which means its being added to the database and still larger than my layout.
Copy linkTweet thisAlerts:
@NogDogMar 31.2011 — Its not returning FALSE, its returning TRUE and not resizing the picture. which means its being added to the database and still larger than my layout.[/QUOTE]

Well, when I run the script, I get a 200x200 image, indicating that it resized the original and saved it to the specified file, so as far as I can tell the resize function is working fine.

One thing I'd try is to add a check on the call to getimagesize() and make sure it's not false (maybe the image file is corrupt or otherwise unreadable by that function?) Also, you may want to cast your calculated resize dimensions to integers in case it does not like a width of 200.333, for example.

Otherwise, if you have a copy of the image in question you don't mind us using to test, you could attach it to a post here so I can try it with that.
Copy linkTweet thisAlerts:
@DerokorianauthorMar 31.2011 — added:

$newHeight = (int)$newHeight;

$newWidth = (int)$newWidth;

before working on the image, to no avail.

You can see how the image is not resized here -> http://dev.rdennispallas.com/index.php?action=view&img=90 and the original I'm uploading from is at -> http://dev.rdennispallas.com/images/_DSC0149.jpg (it exceeds the forums 100k limit)

the thing that gets me, is its properly resizing for the thumbnail...
Copy linkTweet thisAlerts:
@NogDogMar 31.2011 — This seems to work. I think the application of (int) to the width/height calculations fixed it.
[code=php]
function imageResize($src, $target, $newWidth, $newHeight)
{
// $src = original file
// $target = new file
// $newWidth / $newHeight represent maximum dimensions
$sizeInfo = getimagesize($src); // Get original dimensions
if($sizeInfo == false) { die("getimagesize failed");}
list($origWidth, $origHeight) = $sizeInfo;
if ($origWidth > $origHeight) { // set new width/height to maintain aspect ratio
$newHeight = (int)(($newWidth / $origWidth) * $origHeight);
} else {
$newWidth = (int)(($newHeight / $origHeight) * $origWidth);
}
if ($origHeight < $newHeight && $origWidth < $newWidth) {
$newHeight = $origHeight;
$newWidth = $origWidth;
}
$base = imagecreatefromjpeg($src); // open source
$temp = imagecreatetruecolor($newWidth, $newHeight); //create new file
imagecopyresampled($temp, $base, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight); // resample source into new file
if (imagejpeg($temp, $target)) { // copy new file to target location, if successful return true otherwise return false.
return TRUE;
} else {
return FALSE;
}
}
[/code]

You might want to get rid of the die() where I tested the getimagesize() result and just log an error and return false, instead. ?
Copy linkTweet thisAlerts:
@DerokorianauthorMar 31.2011 — still returned true... didn't resize... http://dev.rdennispallas.com/index.php?action=view&img=91 makes me completely confused, here's the rest of my image submit form:
[code=php]
case "imgform":
// Add Image Form
$galqry = "SELECT * FROM {$dbgallerytable}";
$galresult = $db->query($galqry);
$galnum = $galresult->num_rows;
$content .= "<h1>Add Image(s)</h1>
<form action="{$adminurl}?action=gallery&amp;page=imgsub" method="post" enctype="multipart/form-data">
<label for="albsel">Album</label><select name="albsel">
<option value="0" selected>Select Album</option>n";
for( $i=1; $i<=$galnum; $i++ ) {
$galrow = $galresult->fetch_assoc();
$albqry = "SELECT * FROM {$dbalbumtable} WHERE gallery_id='{$galrow['idgallery']}'";
$albresult = $db->query($albqry);
$albnum = $albresult->num_rows;
$content .= "<optgroup label="--- {$galrow['gallery_name']} ---" />n";
for( $o=1; $o<=$albnum; $o++ ) {
$albrow = $albresult->fetch_assoc();
$content .= "<option value="{$galrow['idgallery']},{$albrow['idalbum']}">{$albrow['album_name']}</option>n";
}
}
$content .= "</select>
<label for="image1">Image 1</label><input type="file" name="image1" /><input type="text" name="title1" />
<label for="image2">Image 2</label><input type="file" name="image2" /><input type="text" name="title2" />
<label for="image3">Image 3</label><input type="file" name="image3" /><input type="text" name="title3" />
<label for="image4">Image 4</label><input type="file" name="image4" /><input type="text" name="title4" />
<label for="image5">Image 5</label><input type="file" name="image5" /><input type="text" name="title5" />
<label for="submit">&nbsp;</label><input type="submit" name="submit" value="Submit" /><input type="reset" value="Reset" />
</form>";
break;
case "imgsub":
// Add Image Processing
$ids = explode(",",$_POST['albsel']);
$title = array(0=>''
, $_POST['title1']
, $_POST['title2']
, $_POST['title3']
, $_POST['title4']
, $_POST['title5']
);
$uploaddir = "$sitepath$imgpath$uploadpath";
$content .= "Image Submission<br /><br />";
for( $i=1; $i<=5; $i++ ) {
$content .= "<h4>Image $i</h4>";
if( $_FILES["image{$i}"]['size'] > 1 ) {
list($text,$ext) = explode(".",$_FILES["image{$i}"]['name']);
$filename = "{$title[$i]}-".time()."-{$i}";
$pics = "{$uploaddir}{$filename}_orig.{$ext}";
if( !@getimagesize($_FILES["image{$i}"]['tmp_name']) ) {
$content .= "Image {$i} is not an image.<br />";
} else {
if( $ext != "jpg" && $ext != "jpeg" && $ext != "JPG" && $ext != "JPEG" ) {
$content .= "Only upload jpg images.<br />";
} else {
if( move_uploaded_file($_FILES["image{$i}"]['tmp_name'],$pics) ) {
$tnfile = "{$uploaddir}{$filename}.{$ext}";
$viewfile = "{$uploaddir}{$filename}_1.{$ext}";
$error = 0;
if( imageResize($pics,$tnfile,"200","133") ) {
$content .= "Thumbnail successful.<br />";
} else {
$content .= "Thumbnail failed.<br />";
$error++;
}
if( imageResize($pics,$viewfile,"640","800") ) {
$content .= "View file successful.<br />";
} else {
$content .= "View file failed.<br />";
$error++;
}
if( !unlink($pics) ) $error++;
if( $error == 0 ) {
$insert = "INSERT INTO {$dbimagetable}
(gallery_id,album_id,idimages,image_filename,img_upload_date,image_views) VALUES
('{$ids[0]}','{$ids[1]}',NULL,'{$filename}','".time()."','0')";
if( $db->query($insert) ) {
$content .= "{$filename}.{$ext} added to database.<br />n";
} else {
$content .= "{$filename}.{$ext} database insertion failed!<br />$insert<br />";
}
} else {
$content .= "Errors have occurred and database insertion was not attempted.<br />";
}
} else {
$content .= "{$_FILES["file{$i}"]['name']} did not successfully upload.<br />n";
}
}
}
} else {
$content .= "Error on image{$i}.<br />";
}
}
break;
[/code]
Sorry its not commented I musted been lazy that day!
Copy linkTweet thisAlerts:
@NogDogMar 31.2011 — Changed the logic/math for determining if should base resizing on the width or the height:
[code=php]
function imageResize($src, $target, $newWidth, $newHeight)
{
// $src = original file
// $target = new file
// $newWidth / $newHeight represent maximum dimensions
$sizeInfo = getimagesize($src); // Get original dimensions
if($sizeInfo == false) { die("getimagesize faile");}
list($origWidth, $origHeight) = $sizeInfo;
// new stuff:
$ratio = (($origWidth / $origHeight) > ($newWidth / $newHeight)) ?
$newWidth / $origWidth : $newHeight / $origHeight;
$newWidth = (int) ($origWidth * $ratio);
$newHeight = (int) ($origHeight * $ratio);
// end new stuff
if ($origHeight < $newHeight && $origWidth < $newWidth) {
$newHeight = $origHeight;
$newWidth = $origWidth;
}
$base = imagecreatefromjpeg($src); // open source
$temp = imagecreatetruecolor($newWidth, $newHeight); //create new file
imagecopyresampled($temp, $base, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight); // resample source into new file
if (imagejpeg($temp, $target)) { // copy new file to target location, if successful return true otherwise return false.
return TRUE;
} else {
return FALSE;
}
}[/code]
Copy linkTweet thisAlerts:
@DerokorianauthorApr 01.2011 — ! 5 gold stars, altho I am confused as to why that works... more importantly why it only screwed up that pic for the larger size and worked for the thumbnail... but thank you for your help it is very much appreciated =D

Tested with images of varying initial sizes and ratios... seems to work perfectly now again thanks so much nogdog
Copy linkTweet thisAlerts:
@NogDogApr 01.2011 — I think it *was* resizing, but not as much as you wanted when the image dimensions were such that the ratio of the original width/height was closer to 1 than the ratio of the new widht/height. So that bit of code I added was adapted from an old script I had, such that it compares the aspect ratio of the original image to that of the desired max dimensions in order to figure out which dimension to use to determine the resizing factor.
×

Success!

Help @Derokorian spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...