如何验证上传图片的尺寸。上传图片的尺寸应为100 x 100。
Upload.ts
onFileChange(event) {
let reader = new FileReader();
if (event.target.files && event.target.files.length > 0) {
let file = event.target.files[0];
reader.readAsDataURL(file);
reader.onload = () => {
this.imagePreview = reader.result;
this.employee.photo = reader.result.split(",")[1];
};
}
}
Upload.html
<div class="row">
<div class="col-md-5">
<input type="file" id="avatar"
(change)="onFileChange($event)" #fileInput name="photo">
<p style="color: red">photo should be 100 x 100 size</p>
</div>
</div>
答案 0 :(得分:2)
This answer works fine 但有时它返回高度和宽度为0,这是因为未加载图像。 我只需使用setTimeout-
即可解决此问题let reader = new FileReader();
if (event.target.files && event.target.files.length > 0) {
let file = event.target.files[0];
let img = new Image();
img.src = window.URL.createObjectURL( file );
reader.readAsDataURL(file);
reader.onload = () => {
setTimeout(() => {
const width = img.naturalWidth;
const height = img.naturalHeight;
window.URL.revokeObjectURL( img.src );
console.log(width + '*' + height);
if ( width !== 64 && height !== 64 ) {
alert('photo should be 64 x 64 size');
form.reset();
} else {
this.imgURL = reader.result;
}
}, 2000);
};
答案 1 :(得分:0)
window.URL = window.URL || window.webkitURL;
onFileChange(event) {
let reader = new FileReader();
if (event.target.files && event.target.files.length > 0) {
let file = event.target.files[0];
const img = new Image();
img.src = window.URL.createObjectURL( file );
reader.readAsDataURL(file);
reader.onload = () => {
const width = img.naturalWidth,
const height = img.naturalHeight;
window.URL.revokeObjectURL( img.src );
if( width !== 100 && height !== 100 ) {
this.error = "photo should be 100 x 100 size"
}
this.imagePreview = reader.result;
this.employee.photo = reader.result.split(",")[1];
};
}
}
答案 2 :(得分:0)
您可以使用如下所示的reader.onload()
函数。
reader.onload = () => {
var img = new Image();
img.onload = () => {
console.log(img.width);
console.log(img.height);
// Here you can make use prevention code like shown alert
};
img.src = reader.result; // The data URL
};