Reputation: 833
I am writing code to upload an image file. I need to know the dimensions(height and width) of the image that will be uploaded before I call the function to upload.
Is there a way in angular 2 by which I can extract the image dimension? If so, how?
Upvotes: 13
Views: 34902
Reputation: 1
In component.ts
this.uploadService.validateandUploadFile(files, 300, 300);
In service.ts file
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;
});
}
}
Upvotes: 0
Reputation: 1785
In case if you need to get the image size in ts file:
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;
});
}
Call above method:
const image = {
url: 'https://kalgudi.com/store/assets/images/e-mahila1.jpg',
context: 'Mahila self help group'
}
this.getImageDimension(image).subscribe(
response => {
console.log(response);
}
);
Upvotes: 7
Reputation: 858
I created function to get image size
getImgSize(imageSrc: string): Observable<ISize> {
let mapLoadedImage = (event): ISize => {
return {
width: event.target.width,
height: event.target.height
};
}
var image = new Image();
let $loadedImg = fromEvent(image, "load").pipe(take(1), map(mapLoadedImage));
// Rxjs 4 - let $loadedImg = Observable.fromEvent(image, "load").take(1).map(mapLoadedImage);
image.src = imageSrc;
return $loadedImg;
}
interface ISize { width: number; height: number; }
Also you can subscribe on load event in html
<img (load)="loadedImg($event)" [src]="imageSrc">
and get size from it.
Upvotes: 10
Reputation: 922
Simply you can use following code to get the width and height (Resolution) of the Image.
HTML Code
<img #pic [src]="imgURL" (load)="onLoad()>
In Angular
@ViewChild('pic', { static: false }) pic: ElementRef;
onLoad() {
console.log((this.pic.nativeElement as HTMLImageElement).naturalWidth);
console.log((this.pic.nativeElement as HTMLImageElement).naturalHeight);
}
Upvotes: 5
Reputation: 55443
With the Angular2 approach, I'll create a custom directive to get the height and width of any element. For img
, I'll apply it(directive) in the img
tag and whenever I want to get the height & width of an img, I just need click it. You can modify according to your need.
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';
}
Upvotes: 7
Reputation: 123
You have to use JS code to find the height and width of image as follow :
<!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>
In above code we have to place selected image in image element, after during upload process check height and width and process to upload.
Thanks...
Upvotes: -9