Change width of a image file javascript
If a user selects an image I preview it in a div as background-image, I have 2 input fields ( width , height ) so the user can determine the width and the height of the uploaded image.
I want to resize the preview image if the user changes the width / height.
But I keep getting the error : Uncaught TypeError: Cannot read property 'width' of undefined
Here is my code:
HTML - input fields
<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 - functions
In this function I preview the image and put the image in the image var
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+")" );
}
}
});
});
in this function I want to change the width of the image var which has the file stored into
$(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);
}
});
});
编辑:请把它作为你的input-px onchange事件功能的增强。
链接地址: http://www.djcxy.com/p/78174.html上一篇: 将图像标准化为div
下一篇: 更改图像文件的宽度javascript