更改图像文件 javascript 的宽度

Change width of a image file javascript

本文关键字:javascript 文件 图像      更新时间:2023-09-26

如果用户选择一张图像,我会在div中将其预览为背景图像,我有2个输入字段(宽度,高度),因此用户可以确定上传图像的宽度和高度。

如果用户更改宽度/高度,我想调整预览图像的大小。

但是我一直收到错误:Uncaught TypeError: Cannot read property 'width' of undefined

这是我的代码:

HTML - 输入字段

    <input type="file" name="sourceImage" id="sourceImage">
    <input type="text" class="form-control input-width input-px" maxlength="2" name="width">CM breed
    <input type="text" class="form-control input-height input-px" maxlength="2" name="height">CM hoog

Javascript - 函数

在这个函数中,我预览图像并将图像放入图像变量中

  var image;
  $(function() {
      $("#sourceImage").on("change", function()
      {
          var files = !!this.files ? this.files : [];
          if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support
          if (/^image/.test( files[0].type)){ // only image file
              var reader = new FileReader(); // instance of the FileReader
              reader.readAsDataURL(files[0]); // read the local file
              image = this.result;
              reader.onloadend = function(){ // set image data as background of div
                  $( ".source" ).css( "background-image", "url("+this.result+")" );
              }
          }
      });
  });

在此函数中,我想更改将文件存储到的图像变量的宽度

      $(function(){
      $(".input-px").on("change", function()
      {
          image.width($(".input-width").val());
      })
  })
$(function(){
    $(".input-px").on("change", function() {
        var _width = parseInt($(".input-width").val(), 10) || 0;
        var _height = parseInt($(".input-height").val(), 10) || 0;
        if(_width > 0) {
            image.width(_width);
        }
        if(_height > 0) {
            image.width(_height);
        }
    });
});

编辑:请将其作为输入px onchange事件功能的增强功能。