Jump to content

image resizing code not working properly


JJBlaha

Recommended Posts

I am trying to resize an image before it is uploaded.  If I only have

[code]
$uploadedfile = $imagefile;

$src = imagecreatefromjpeg($uploadedfile);
list($width,$height)=getimagesize($uploadedfile);

$newwidth=600;
$newheight=($height/$width)*600;

...rest of code
[/code]

It works, but only if the width exceeds 600px.  If i try to do this

[code]
$uploadedfile = $imagefile;

$src = imagecreatefromjpeg($uploadedfile);
list($width,$height)=getimagesize($uploadedfile);

if($width > 600) {
$newwidth=600;
$newheight=($height/$width)*600;
) else {
if($height > 600) {
$newheight=600;
$newwidth=($width/$height)*600;
)
}
[/code]

I get an error and the page does not load.  Any ideas?
Link to comment
https://forums.phpfreaks.com/topic/34761-image-resizing-code-not-working-properly/
Share on other sites

for resizing something to a max width/height, consider something like this instead when working out the new width/height:

[code]
<?php
$scale = min($max_width / $actual_width, $max_height / $actual_height);

// scale < 1 means image needs to be shrunk
if ($scale < 1)
{
  $new_width = $scale * $sx;
  $new_height = $scale * $sy;

  ... imagecopyresampled, etc all goes here ....

  ...draw the now resized image...
}
else // otherwise, just output the image as normal
{
  .... draw the image as normal...
}
?>
[/code]
[code]
<?php
function createThumbnail($imageDirectory, $imageName, $thumbDirectory, $thumbWidth = 120, $quality = 100){
$details = getimagesize("$imageDirectory/$imageName") or die('<div class="container">
<div class="content">
Please only upload images.
</div>
</div>');
$type = preg_replace('@^.+(?<=/)(.+)$@', '$1', $details['mime']);
eval('$srcImg = imagecreatefrom'.$type.'("$imageDirectory/$imageName");');
$thumbHeight = $details[1] * ($thumbWidth / $details[0]);
$thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $details[0], $details[1]);
eval('image'.$type.'($thumbImg, "$thumbDirectory/$imageName"'.(($type=='jpeg')?', $quality':'').');');
imagedestroy($srcImg);
imagedestroy($thumbImg);
}

//This can create thumbs, or resize
//keep original_image/directory and resized_image/directory the same to make a resized image
//keep original_image/directory and resized_image/directory different to make a thumbnail
createThumbnail("original_image/directory", image_name.jpg, "resized_image/directory");
?>
[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.