I have a button which uploads a background image to a folder and saves the file name to the database, but I cant figure how to re size the image before uploading it. Actually I am facing two problems. 1 - How to resize the image and upload it. 2 - How to display the image as background image for a div which is having a different dimension.

What I have done till now :

Html

<div class="image_load_div">
 <form id="imageform" enctype="multipart/form-data" method="post" action="upload.php">
   <input name="photoimg" id="photoimg" type="file"/>
 </form>
</div>

javascript

$("#imageform").ajaxForm().submit(); 

php- upload file

$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
   name = $_FILES['photoimg']['name'];
   $size = $_FILES['photoimg']['size'];
   if(strlen($name)) {
 list($txt, $ext) = explode(".", $name);
 if(in_array($ext,$valid_formats)) {
   if($size<(1024*1024)) {
          session_start();
      $id = $_SESSION['QuestionId'];
      $path = "/images/Img/".$id."_bg.".$ext;

          if( move_uploaded_file($_FILES["photoimg"]["tmp_name"],$path) ) {
             // Save the file name into database
          }
        else { echo "<script>alert('Upload failed');</script>"; }
   else { echo "<script>alert('Image file size max 1 MB');</script>"; }                 
    else {  echo "<script>alert('Invalid file format..');</script>"; }  
 else { echo "<script>alert('Please select image..!');</script>";   exit; }

I would like to save the image as height:408px; width:490px; and when displaying the image I want to display this image width:174px; height:108px; IMP !During uploading and when displaying, need to consider the aspect ratio;
for now uploading is working.

please help me to solve this. Thanks.

Dani AI

Generated

Short version: add a resize step (server-side is simplest and most reliable) that preserves aspect ratio, then generate a thumbnail for display. you don’t currently have resize logic; is right that you need to add it. Below are practical examples you can drop into upload handling, plus tips for showing the image as a DIV background without distortion.

function resize_image($src, $dst, $maxW, $maxH, $crop=false, $quality=85) {
  if (!file_exists($src)) return false;
  $info = getimagesize($src); if (!$info) return false;
  list($srcW,$srcH,$type) = $info;
  switch ($type) {
    case IMAGETYPE_JPEG: $srcImg = imagecreatefromjpeg($src); break;
    case IMAGETYPE_PNG:  $srcImg = imagecreatefrompng($src);  break;
    case IMAGETYPE_GIF:  $srcImg = imagecreatefromgif($src);  break;
    default: return false;
  }
  if ($crop) {
    $ratio = max($maxW/$srcW, $maxH/$srcH);
    $tmpW=(int)($srcW*$ratio); $tmpH=(int)($srcH*$ratio);
    $tmp = imagecreatetruecolor($tmpW,$tmpH);
    if ($type==IMAGETYPE_PNG){ imagealphablending($tmp,false); imagesavealpha($tmp,true); }
    imagecopyresampled($tmp,$srcImg,0,0,0,0,$tmpW,$tmpH,$srcW,$srcH);
    $x=(int)(($tmpW-$maxW)/2); $y=(int)(($tmpH-$maxH)/2);
    $dstImg=imagecreatetruecolor($maxW,$maxH);
    if ($type==IMAGETYPE_PNG){ imagealphablending($dstImg,false); imagesavealpha($dstImg,true); }
    imagecopy($dstImg,$tmp,0,0,$x,$y,$maxW,$maxH); imagedestroy($tmp);
  } else {
    $ratio = min($maxW/$srcW, $maxH/$srcH);
    $newW=(int)($srcW*$ratio); $newH=(int)($srcH*$ratio);
    $dstImg=imagecreatetruecolor($newW,$newH);
    if ($type==IMAGETYPE_PNG){ imagealphablending($dstImg,false); imagesavealpha($dstImg,true); }
    imagecopyresampled($dstImg,$srcImg,0,0,0,0,$newW,$newH,$srcW,$srcH);
  }
  switch ($type) { case IMAGETYPE_JPEG: imagejpeg($dstImg,$dst,$quality); break;
    case IMAGETYPE_PNG: imagepng($dstImg,$dst); break; case IMAGETYPE_GIF: imagegif($dstImg,$dst); break;
  }
  imagedestroy($srcImg); imagedestroy($dstImg); return true;
}

Usage example (from the uploaded tmp file, create both saved image and thumbnail):

resize_image($_FILES['photoimg']['tmp_name'],"/images/Img/{$id}_bg.jpg",490,408,false);
resize_image($_FILES['photoimg']['tmp_name'],"/images/Img/{$id}_thumb.jpg",174,108,true);

To display as a background without stretching, use CSS:

.my-bg {
  width:174px; height:108px;
  background-image:url('/images/Img/123_bg.jpg');
  background-position:center center;
  background-repeat:no-repeat;
  background-size:cover; /* cover crops to fill, use 'contain' to fit entirely */
}

Troubleshooting/cautions: validate MIME with getimagesize(), check $_FILES['photoimg']['error'], ensure GD is installed (function_exists('gd_info')), watch php.ini limits (upload_max_filesize, post_max_size, memory_limit), and keep the original image if you may need different sizes later. Client-side resizing with a canvas can reduce upload size but server-side resizing is still recommended for consistency.

Member Avatar for Member #949455

I would like to save the image as height:408px; width:490px; and when displaying the image I want to display this image width:174px; height:108px; IMP !During uploading and when displaying, need to consider the aspect ratio;

I don't see any code you provided that has a resize image code in it. You need to add one

This is the closest one code that is related to resized:

if($size<(1024*1024)) {

If you didn't write this code most likely you have to change it from there.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.