I am currently working on creating centered and cropped thumbnails for images retrieved from a database. I came across some helpful information on how to achieve this:
The resource I found is written for JavaScript, but I am using Angular 7. I am facing difficulties in determining whether an image is portrait or landscape orientation.
My approach was to add a "portrait" class to the images obtained before displaying them on the page. However, since the image paths are coming from the database, I created an Image object to handle this logic:
getPhotosUser(page) {
this._photoService.getPhotosUser(this.user.id, page).subscribe(
response => {
this.photos = response.objects
var addImageOrientationClass = function (img) {
var imgObject = new Image();
imgObject.src = img;
if(imgObject.naturalHeight > imgObject.naturalWidth){
img.classList.add("portrait")
}
}
this.photos.forEach(function (value: any) {
console.log("PHTOOOSOASAOSIA")
value.path = environment.api.replace('/api', '/') + value.path.replace('app/', '');
addImageOrientationClass(value.path)
})
}
)
}
However, I encountered the following error:
ERROR TypeError: Cannot read property 'add' of undefined
I also attempted executing similar code in ngAfterViewInit, but the images array appeared to be empty, resulting in no images displayed as expected. Here's a snippet of my code:
ngAfterViewInit() {
var addImageOrientationClass = function (img) {
console.log(typeof(img))
if (img.naturalHeight > img.naturalWidth) {
img.classList.add("portrait")
}
}
var images = document.querySelectorAll("thumbnail img");
images.forEach(function (value: any){
if (value.complete){
addImageOrientationClass(value)
}else{
value.addEventListener("load", function(evt){
addImageOrientationClass(evt.target)
})
}
})
}
If anyone can offer assistance or suggest a useful library for achieving this functionality, it would be greatly appreciated. Thank you in advance.