hi, as the title says, i want to resize and preview image before i submit it to my server. it is because of reducing load to my server and also give the client ability to crop the image too.

i am using imgareaselect for cropping. and also using a javascript to preview the image. until now this works well.

i wanted to resize the image before crop and upload, so i search a bit and found that i can use canvas for resizing while maintaining the ratio.

but after updated my code this does not works. i am new to javascript. i need your help.
my script

<link rel="stylesheet" type="text/css" href="css/imgareaselect-default.css" />
<script type="text/javascript" src="scripts/jquery.min.js"></script>
<script type="text/javascript" src="scripts/jquery.imgareaselect.pack.js"></script>
<script type="text/javascript">

function previewImage(input) {

    var preview = document.getElementById('preview');
    var preview_crop_thumb = document.getElementById('preview_crop_thumb');

    if (input.files && input.files[0]) {

      var img = document.createElement("img");
      var reader = new FileReader();

      reader.onload = function (e) {
      img.src = e.target.result
      }

      reader.readAsDataURL(input.files[0]);
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0);

      var MAX_WIDTH = 550;
      var MAX_HEIGHT = 550;
      var width = img.width;
      var height = img.height;

      if (width > height) {
      if (width > MAX_WIDTH) {
      height *= MAX_WIDTH / width;
      width = MAX_WIDTH;
    }
    } else {
      if (height > MAX_HEIGHT) {
      width *= MAX_HEIGHT / height;
      height = MAX_HEIGHT;
    }
    }
      canvas.width = width;
      canvas.height = height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, width, height);
      var dataurl = canvas.toDataURL("image/jpg");

      window.onload=function(){

      document.getElementById('preview').style.display='block';
      document.getElementById('preview_crop').style.display='block';
      document.getElementById('image_crop_diolouge').style.display='block';
      preview.setAttribute('src', dataurl);
      preview_crop_thumb.setAttribute('src', dataurl);  
    }


    } else {

      document.getElementById('preview').style.display='none';
      document.getElementById('preview_crop').style.display='none';
      document.getElementById('image_crop_diolouge').style.display='none';
      preview.setAttribute('src', 'placeholder.png');
      preview_crop_thumb.setAttribute('src', 'placeholder.png');

    }
  }

</script>
<style>
.image_crop_diolouge{
    font-family: calibri;
    color:#7A7A7A;
    text-shadow:0px 1px 1px #BDBDBD;
    font-weight:bold;
    margin:10px; 
    background:#FFE974; 
    border:1px solid #FFB28E; 
    box-shadow:1px 1px 2px #666; 
    border-radius:1px; 
    max-width:800px;
    padding:10px; 
    }
#preview_crop{
    width: 200px; 
    height: 200px; 
    overflow: hidden; 
    float:right; 
    display:none; 
    margin:10px 20px 10px 0px; 
    }
#preview{
    width:550px; 
    height:550px; 
    display:none; 
    float:left;
    margin:10px 10px 10px 20px; 
    }   

</style>
<center>
<div style="max-width:800px; ">
<div class="image_crop_diolouge" id="image_crop_diolouge" style="display:none;">Press the left mouse button and drag to crop the image</div>
<img id="preview" src="placeholder.png"/>
<div id="preview_crop" >
<img id="preview_crop_thumb" src="placeholder.png" style="width: 200px;">
</div>
<div class="image_crop_diolouge">
<input type="file" name="image" onchange="previewImage(this)" accept="image/*"/>
</div>
<br/><br/>
</div>
</center>

Dani AI

Generated

Quick diagnosis for : two things are breaking your current flow — the image is used before it finishes loading, and canvas is never created/defined where you call getContext. Also avoid using window.onload inside the file handler; that runs on page load, not when the file finishes processing. Fix the sequence so you (1) obtain the File, (2) create an Image (or use createImageBitmap), (3) wait for the image to load, (4) create/draw to a canvas, then (5) produce a blob/dataURL for preview or upload.

A minimal, reliable pattern (uses URL.createObjectURL and canvas.toBlob) — adapt to your DOM and imgAreaSelect initialization:

function handleFileInput(input) {
  const file = input.files && input.files[0];
  if (!file) return;
  const img = new Image();
  img.onload = () => {
    const MAX = 550;
    let w = img.width, h = img.height;
    if (w > h && w > MAX) { h = h * (MAX / w); w = MAX; }
    else if (h > w && h > MAX) { w = w * (MAX / h); h = MAX; }

    const canvas = document.createElement('canvas');
    canvas.width = w; canvas.height = h;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0, w, h);

    canvas.toBlob(blob => {
      const url = URL.createObjectURL(blob);
      document.getElementById('preview').src = url;
      // re-initialize or update imgAreaSelect on #preview here
    }, 'image/jpeg', 0.9);
  };
  img.src = URL.createObjectURL(file);
}

When the user makes a selection with imgAreaSelect, map the selection back to the canvas coordinates (scale = canvas.width / displayedWidth) and crop using drawImage(sourceCanvas, sx, sy, sw, sh, 0, 0, destW, destH) to get the final upload blob. Use FormData and append the final blob to reduce server load.

Quick tips: check console errors, use 'image/jpeg' (not 'image/jpg'), prefer toBlob over toDataURL for uploads (less memory), and handle EXIF orientation for phone photos (use a small EXIF helper if needed). As pointed out, resizing the CSS display with jQuery doesn’t reduce upload size — canvas resizing does. Useful references: File API and HTMLCanvasElement.toBlob.

Recommended Answers

All 3 Replies

hello! is there anyone who can help me????

Not a canvas expert but I may be able to help. What doesn't work? Any javascript errors in the console?

Did you think about using jQuery 'resize' instead of a canvas approach since imageareaselect is already jQuery?

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.