Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

179
Vistas
Implement Javascript image resize

I'm trying to fix Canvas Resize (Downscale) Image, I got jsfiddle http://jsfiddle.net/EWupT/ for image resizing. i have html input field when user upload instantly image show on input field, When adding resize code on my exiting code i got an error. any help greatly appreciated.

My JS:

    $(document).ready(function() {
    var readURL = function(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');
                canvas.width=300;
                canvas.height=234;
                ctx.drawImage(reader, 0, 0, 300, 234);

                $('.profile-pic').attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }

    $(".file-upload").on('change', function(){
        readURL(this);
    });
    $(".upload-button").on('click', function() {
       $(".file-upload").click();
    });
});

My HTML:

<div class="upload-button" id="imageresize"><img class="profile-pic"  src="../images/add-image.png" /></div>
<input id="formFile" id="avatar-2" class="file-upload" type="file" name="my_file"  accept="image/*">

I got this error:

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLCanvasElement or HTMLImageElement or HTMLVideoElement or ImageBitmap or OffscreenCanvas or SVGImageElement or VideoFrame)'.
    at FileReader.reader.onload
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Added filereader.onload function, inside we can use resize code. Updated code:

$(".upload-button").on('click', function() {
  $(".file-upload").click();
});
var fileReader = new FileReader();

fileReader.onload = function(event) {
  var image = new Image();

  image.onload = function() {
    var canvas = document.createElement("canvas");
    var context = canvas.getContext("2d");
    canvas.width = 500;
    canvas.height = 380;
    //canvas.height=image.height/1;

    $('#upload-preview').width(500); //pixels

    var hRatio = canvas.width / image.width;
    var vRatio = canvas.height / image.height;
    var ratio = Math.min(hRatio, vRatio);

    context.drawImage(image, 0, 0, image.width, image.height, 0, 0,
      image.width * ratio, image.height * ratio
    );

    document.getElementById("upload-preview").src = canvas.toDataURL();
  }
  image.src = event.target.result;
};

var uploadImage = function() {
  var uploadImage = document.getElementById("upload-Image");

  if (uploadImage.files.length === 0) {
    return;
  }

  var uploadFile = document.getElementById("upload-Image").files[0];
  fileReader.readAsDataURL(uploadFile);
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Since you are using the new Image() function and generating a HTMLImageElement object dynamically, add img.src after the onload function like so:

img = new Image();
img.onload = function(){
  var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    canvas.width=300
    canvas.height=234
    ctx.drawImage(img, 0, 0, 300, 234);
    document.body.appendChild(canvas);
};
img.src = 'http://i.imgur.com/SHo6Fub.jpg';
<img src="http://i.imgur.com/SHo6Fub.jpg" width="300" height="234">

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda