Uncovering the Image Orientation in Angular: Is it Possible to Determine the Direction Post-view or Upon Retrieval from Database?

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.

Answer №1

To summarize your issue, you need to retrieve images from a database and display them as centered and cropped thumbnails.

Here's the basic approach for implementation:

a) Thumbnail: Wrap the image tag inside an anchor tag to create a thumbnail.

b) Centered and cropped: Apply the same CSS styles mentioned in the documentation you referenced.

c) Loading Images Dynamically:

 1) Create placeholders for the anchor->image tag nested within your photos array
 2) Map the image source dynamically: <img [src]="urlVariable" />

PS: The JavaScript code you mentioned is just for reference on how to create Image elements dynamically in Angular. For more information on rendering elements in Angular, you can visit:

Angular-renderer

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Spontaneous visual paired with text upon refreshing

I am new to Java script and I am working on creating a web page that displays two random numbers every time it is refreshed. Depending on these numbers, specific text should be shown. These numbers are represented by images ranging from 0 to 5. Currently ...

Retrieve an established SQS eventSource in AWS CDK

When working with AWS CDK, there is a built-in function called addEventSource that allows you to easily add new SQS triggers (eventSources) to a lambda function. However, I'm curious if there is a way to access and modify the existing eventSources ass ...

Eliminate the X-Powered-By:express response header from the Angular UI navigation URL

When using the application, I am not seeing the header x-powered-by in the response headers, which is functioning as intended. The issue occurs when a user refreshes the page, causing the x-powered-by header to be added to the response header in the devel ...

How can you create a unique custom border for an image and display it on another image?

I am working towards achieving a specific output similar to the one shown in this https://i.stack.imgur.com/ejiYC.png image. Currently, I have successfully created the border section. Now, my next challenge is how to overlap images and apply borders as de ...

Is JsonEditor capable of editing JSON Schemas effectively?

For a while now, I have been impressed by the functionality of JSON-editor and have been using it to edit documents based on a specific JSON schema. But why stop there? Many users utilize JSON-Editor to make changes to JSON documents according to the corr ...

Ways to automatically change a URL into a clickable link upon pasting

When attempting to paste a URL into the text box such as https://stackoverflow.com/, it does not automatically convert to a hyperlink. I previously tried using regular expressions in this related question. The function I implemented worked correctly, howe ...

What is the best way to eliminate a trailing backslash from a string?

Currently, I am iterating through a list of Discord server names in node.js. The goal is to create a php file that contains an array structured like this: <?php $guildLookup = array( "164930842483761" => "guildName1", "56334 ...

What is the best way to automatically insert data into a database at regular intervals, while ensuring that users are unable to manipulate the timing through inspect

Is there a secure way to insert 1 point into the database every x seconds without allowing users to manipulate the interval time through inspect element? var time = 1; var interval = setInterval(function() { if (time != time + 1) { ...

Issue encountered when using await in Tensorflow.js sample code with TypeScript

After going through the official tensorflow.js documentation, I attempted to test this example using typescript with tensorflow.js While trying to execute the code snippet provided in the tensorflow.js documentation, I encountered an error related to the ...

Generate a JSON object specifically for the modified input fields upon submitting the form

Is there a way to generate a JSON object only with the input fields that have been modified before submitting the form? How can I capture and store each changed value in the form as JSON data? $(document).ready(function() { $('#save').clic ...

Parsing JSON results in the return of two objects

I am analyzing a JSON file, expecting it to return Message[] using a promise. This code is similar to the one utilized in the Heroes sample project found in HTTP documentation { "data": [ {"id":"1","commid":"0","subject":"test1subject","body":" ...

Guidelines for securing login access where the "IsApproved" field must be true before authorization

During the account registration process, I initially set the default value to false for the field IsApproved. I need to create security rules that allow login only for users with IsApproved:true, and redirect those with IsApproved:false to the accessdenied ...

Wrap the text in Alphine using PHP

Currently, I am dealing with a situation where I have a string that needs to be wrapped using the Yii tag like Yii::t('app' , 'what_string'). The reason for this is because I require it to be translated per string on another page. Howev ...

What steps can I take to reset my JavaScript code once its original purpose has been fulfilled?

I created this code, learning as I went along. It measures Beats Per Minute as one clicks the left-mouse-button each time they feel a pulse. After 10 clicks, the JavaScript code takes all the values in the array and calculates an average BPM. The issue ar ...

Solving the checkbox toggle challenge with recursive functions | Recursive checkbox challenge

I'm currently working on creating a checkbox tree with the following data structure for items const checkboxes = [{ field: 'ARTICLE', id: 41, name: 'Article', parentId: null, checked: false, children: [ ...

What could be the reason behind the malfunction of this jQuery post request?

I am currently studying AJAX with jQuery, but I am facing an issue with my registration system. The following code does not seem to work: $('#submitr').click(function () { var username = $('#usernamefieldr').val(); var password ...

Tips on adjusting the rotation speed of an Angular Material progress-spinner

For my web project, I have incorporated a material progress spinner. However, I am finding that it rotates at a very slow speed. Is there anyone who knows how to increase the rotation speed of this spinner? ...

Efficient method to activate openLayers 3 'singleClick' event from karma test

We are incorporating angular2 and openlayers3 to showcase a map on our webpage. The singleClick feature is utilized to exhibit a popup when the marker on the map is clicked - this.map.on('singleclick', (e) => { this.showW ...

Ways to showcase HTML table in a four-column layout/grid

Delving into Dynamic HTML table creation, I'm currently using jquery for rendering purposes. At the moment, I am only displaying the table. The Goal I aim to segment my table into four columns or a grid structure Something akin to this: https://i. ...

Utilizing Vue 3's Inject Plugin alongside the powerful Composition API and TypeScript

I developed a controller plugin to be used globally in all components, but I am facing challenges making it compatible with Vue 3 + TypeScript + Composition API as I keep getting a TypeScript error. ui/plugins/controllers.ts import { App } from 'vue& ...