我正在编写代码来上传图片文件。在调用要上传的函数之前,我需要知道要上传的图像的尺寸(高度和宽度)。
在角度2中是否有一种方法可以提取图像尺寸?如果是这样,怎么样?
答案 0 :(得分:3)
我创建了获取图像大小的函数
getImgSize(imageSrc: string): Observable<ISize> {
let mapLoadedImage = (event): ISize => {
return {
width: event.target.width,
height: event.target.height
};
}
var image = new Image();
let $loadedImg = Observable.fromEvent(image, "load").take(1).map(mapLoadedImage);
image.src = imageSrc;
return $loadedImg;
}
interface ISize { width: number; height: number; }
您也可以在html中订阅加载事件
<img (load)="loadedImg($event)" [src]="imageSrc">
并从中获取大小。
答案 1 :(得分:2)
使用Angular2方法,我将创建一个自定义指令来获取任何元素的高度和宽度。对于img
,我会在img
标记中应用它(指令),每当我想要获得高度&amp;一个img的宽度,我只需要点击它。您可以根据需要进行修改。
DEMO:https://plnkr.co/edit/3tibSEJCF734KQ3PBNZc?p=preview
<强> directive.ts 强>
import { Directive,Input,Output,ElementRef,Renderer} from '@angular/core';
@Directive({
selector:"[getHeightWidth]",
host:{
'(click)':"show()"
}
})
export class GetEleDirective{
constructor(private el:ElementRef){
}
show(){
console.log(this.el.nativeElement);
console.log('height---' + this.el.nativeElement.offsetHeight);
console.log('width---' + this.el.nativeElement.offsetWidth);
}
}
<强> app.ts 强>
@Component({
selector: 'my-app',
template: `
<div style="width:200px;height:300px">
<img getHeightWidth <!-- here I'm using getHeightWidth directive-->
[src]="source" alt="Angular2"
width="100%"
height="100%">
</div>
`,
})
export class AppComponent {
source='images/angular.png';
}
答案 2 :(得分:1)
如果必须在ts文件中获取图像大小:
getImageDimension (image): Observable<any> {
return new Observable(observer => {
const img = new Image();
img.onload = function (event) {
const loadedImage: any = event.currentTarget;
image.width = loadedImage.width;
image.height = loadedImage.height;
observer.next(image);
observer.complete();
}
img.src = image.url;
});
}
调用上述方法:
const image = {
url: 'https://kalgudi.com/store/assets/images/e-mahila1.jpg',
context: 'Mahila self help group'
}
this.getImageDimenstion (image).subscribe(response => {
console.log(response);
});
答案 3 :(得分:1)
只需使用以下代码即可获取图像的宽度和高度(分辨率)。
HTML代码
<img #pic [src]="imgURL" (load)="onLoad()>
在Angular中
@ViewChild('pic', { static: false }) pic: ElementRef;
onLoad() {
console.log((this.pic.nativeElement as HTMLImageElement).naturalWidth);
console.log((this.pic.nativeElement as HTMLImageElement).naturalHeight);
}
答案 4 :(得分:0)
在 component.ts
this.uploadService.validateandUploadFile(files, 300, 300);
在 service.ts 文件中
import { Injectable } from '@angular/core';
import * as AWS from 'aws-sdk/global';
import * as S3 from 'aws-sdk/clients/s3';
import { BehaviorSubject } from 'rxjs';
FOLDER = '/';
imageUrl = "";
resData: BehaviorSubject<any> = new BehaviorSubject(null);
data = { message: "", data: "" };
constructor() { }
validateandUploadFile(file, Iheight, Iwidth) {
let fileToUpload = file;
if (fileToUpload.type == "image/jpeg" || fileToUpload.type == "image/png" || fileToUpload.type == "image/jpeg") {
//Show image preview
let reader = new FileReader();
reader.onload = (event: any) => {
var img = new Image();
img.onload = () => {
let width = img.width;
let height = img.height;
if (width <= Iwidth && height <= Iheight) {
this.imageUrl = event.target.result;
this.uploadfile(file);
} else {
this.data.message = "You can maximum upload " + Iheight + " * " + Iwidth + " File";
this.data.data = "";
this.resData.next(this.data);
return this.resData;
}
};
img.src = event.target.result;
}
reader.readAsDataURL(fileToUpload);
} else {
this.data.message = "You can't be able to upload file except JPG and PNG format";
this.data.data = "";
this.resData.next(this.data);
return this.resData;
}
}
uploadfile(file) {
if (file != null) {
const bucket = new S3(
{
accessKeyId: '***********************',
secretAccessKey: '**********************************',
region: 'us-east-2'
}
);
const params = {
Bucket: '*********',
Key: file.name,
Body: file,
ACL: 'public-read'
};
var that = this;
bucket.upload(params, function (err, data) {
if (err) {
console.log('There was an error uploading your file: ', err);
return false;
}
console.log('Successfully uploaded file.', data);
that.data.message = "Successfully uploaded file.";
that.data.data = data.Location;
that.resData.next(that.data);
return that.resData;
});
}
}
答案 5 :(得分:-6)
您必须使用JS代码来查找图像的高度和宽度,如下所示:
<!DOCTYPE html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
function readURL(input)
{
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#image1')
.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
function upload()
{
var img = document.getElementById('image1');
var width = img.clientWidth;
var height = img.clientHeight;
alert(width + " : " + height);
//check height and width using above two variables (width/height) in if block and place upload code in if block...
}
</script>
</head>
<body>
<input type='file' onchange="readURL(this);" /><input type="button" value="Upload" onClick="upload()" /><br>
<img id="image1" src="#" alt="your image" height="auto" width="auto" />
</body>
</html>
在上面的代码中,我们必须在图像元素中放置所选图像,在上传过程中检查高度和宽度以及上传过程。
...谢谢