Leveraging the Jpeg-autorotate npm package to automatically adjust image orientation according to EXIF data in JavaScript

Struggling with an issue in my web app where uploaded images display sideways, I decided to utilize this module to rotate images based on the EXIF data.

Here's a snippet of my code:

 <template>
  <div :class="$style.form247">
    <Canvas :url="image" :value="value" @input="$emit('input', $event)" />
      <div :class="$style.file">
      Choose file
      <input :class="$style.input" type="file" @change="onFileUpload">
    </div>
  </div>
</template>


<script>

import Canvas from './Canvas'

const jo = require('jpeg-autorotate')
const options = {quality: 100}



export default {
  props: ['value'],
  components: {
    Canvas
  },
  data() {
    return {
      image: null
    }
  },
  methods: {
    onFileUpload(event) {
      const selectedFile = event.target.files[0]
      const reader = new FileReader()


        const myBuffer = jo.rotate(selectedFile, options)
        .then(({buffer, orientation, dimensions, quality}) => {
          console.log(`Orientation was ${orientation}`)
          console.log(`Dimensions after rotation: ${dimensions.width}x${dimensions.height}`)
          console.log(`Quality: ${quality}`)
          // ...Do whatever you need with the resulting buffer...
          return buffer
        })
        .catch((error) => {
          console.log('An error occurred when rotating the file: ' + error.message)
        })

      reader.onload = (e) => this.image = e.target.result



      reader.readAsDataURL(selectedFile)

    }
  }
}
</script>

Encountering an error during application execution related to the jo.rotate function not receiving the correct parameters, despite passing them through the selectedFile constant. Reviewing examples in the documentation under sample usage provided some guidance, but I remain puzzled about integrating the rotate function within my code. Should I save the results of jo.rotate into a variable like this?

const myBuffer = jo.rotate(selectedFile, options)
.then(({buffer, orientation, dimensions, quality}) => {
  console.log(`Orientation was ${orientation}`)
  console.log(`Dimensions after rotation: ${dimensions.width}x${dimensions.height}`)
  console.log(`Quality: ${quality}`)
  // ...Do whatever you need with the resulting buffer...
  return buffer
})
.catch((error) => {
  console.log('An error occurred when rotating the file: ' + error.message)
})

If so, should I then pass it to the readAsDataURL function like this: reader.readAsDataURL(myBuffer)?

I suspect that my placement of the jo.rotate function is incorrect and may belong inside the reader.onload function due to my limited JavaScript knowledge. Any insights on where to correctly position this function would be greatly appreciated.

Answer №1

Unfortunately, the jpeg-autorotate feature doesn't function within the browser environment. To resolve this issue, you will need to utilize an exif parsing library to extract the orientation data and manually rotate the image using CSS transform:rotate(...) or canvas.

For efficient orientation parsing, I would suggest utilizing exifr. This library is known for its speed and ability to handle large quantities of photos without causing browser crashes or long processing times :). Additionally, it offers a simple API that can process various types of inputs - such as elements, URLs, Buffers, ArrayBuffers, base64 URLs, strings, and more.

exifr.orientation(file).then(value => {
  console.log('orientation:', value)
})

This function returns an integer ranging from 1 to 8 (for further details on these values, refer to this resource)

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

The process of setting up a carousel for tables using jQuery

I can successfully implement jquery for an image carousel, but now I need to find a way to create a sliding table format. Any assistance on this matter would be greatly appreciated. Here is the code I currently have: <ul> <li><a style= ...

Within jQuery lies the power to perform multiplication operations effortlessly

I'd like to accomplish this using jQuery: var menuItems = document.getElementsByTagName("li"); for (var k = 0; k < menuItems.length; k++) { if (menuItems[k].className == "menu") { var child = menuItems[k].firstChild; if ...

The provider for authentication, which is linked to the AuthenticationService and subsequently to the loginControl, is currently unidentified

Attempting to implement an authentication service in my application, I encountered an error when trying to call it within my controller: !JavaScript ERROR: [$injector:unpr] Unknown provider: AuthenticationServiceProvider <- AuthenticationService <- ...

Tips for implementing $routeProvider's resolve function in electron-angular-boilerplate

I am encountering an issue with loading JSON data before entering the main controller in my project. Using this project as a template, I made alterations to only dist/app/home/home.js where the changes were implemented: angular.module('WellJournal&a ...

`What is the best way to employ the Return statement in programming?`

Trying to grasp the concepts of functions and methods has been a challenge for me. I often find myself confused about when, where, and how to use return statements in different situations. To illustrate this confusion, let's take a look at two code sn ...

I'm having trouble with my Typescript file in Vscode - every time I try to edit the css code, all the text turns red. Can someone

Check out this visual representation: [1]: https://i.stack.imgur.com/9yXUJ.png Followed by the corresponding code snippet. export const GlobalStyle = createGlobalStyle` html { height: 100%; } body { background-image: url(${BGImage}); ba ...

Ways to center your attention on the Textbox

I am currently developing a chat program using JavaScript, HTML, and CSS. How can I set the focus on the input field for typing messages? Is it usually done with CSS code? Here is the current CSS styling for my message input field: Code: #messageField ...

What is the proper way to refer to an array or object within a function in JavaScript

Greetings! I am facing an issue with a JavaScript array declared outside of a function as shown below: var daily = []; daily["data"]=[]; daily["data"].push('hello'); function demo() { console.log(daily); // not working here } Can anyone advise ...

All menus effortlessly sliding out simultaneously

I'm having an issue with my navigation bar. I want each link to slide its corresponding DIV up or down when clicked. However, all the DIVs are sliding and when clicking on the same link everything slides up. How can I fix this problem? This is my HT ...

Erase a chat for only one user within a messaging application

Currently, I am in the process of building a chat application using nodejs and mongodb. In order to structure my database properly, I have created two models: conversation and messages. Message.js conversationId: { //conversationID }, body: ...

Why won't my setTimeout function work?

I'm having trouble working with the setTimeout function, as it doesn't seem to be functioning properly. First and foremost, Player.prototype.playByUrl = function (url) { this.object.data = url; return this.play(); } The co ...

Attempting to send an array of files to a Meteor function

When calling a method within a submit button event, the code looks like this: 'submit #form': function(event, tmpl){ var files = null; if(event.target.fileInput) files = event.target.fileInput.files; console.log(f); Met ...

Mongoose fails to store a newly created document

I am trying to store a MongoDB document in my Node server using Mongoose: mongoose.connect('mongodb://localhost/appJobs'); var db = mongoose.connection; db.on('error', function() {console.log("error")}); db.once('open', funct ...

Review all the information in the Excel spreadsheet

I aim to extract data from the initial row, execute an operation on it, record the outcome, then proceed to the subsequent rows until all the data in the Excel file has been processed. Here are some queries I have: Why are the iterators not functioning ...

Using yajrabox to create a loop in Laravel for Datatables through an ajax call

function generateDataTableWithDates(tgl = null, tglA = null, tglB = null, departemenId = null, group = true){ setColumn(group); var tgl = {}; for (var i=1; i < 32; i++) { tgl[i] = i; }; $('.tableCustom3 ...

The Ajax form is failing to send data to PHP

Thanks to Stackoverflow, I've been diving into website design. I recently put together some code for handling data sent from an HTML form using Ajax. The code does a good job of error checking, but it seems to be missing the step of actually sending t ...

Hidden Password Field Option in HTML

My HTML password textbox has the input type set as password, but I can still see what is being typed. This shouldn't happen as password inputs should be masked. Can someone please advise me on how to resolve this issue? To replicate, copy the code be ...

Temporary redirection of external links page

There is a specific feature I am trying to implement on my website, but I am having trouble figuring out how to make it work seamlessly. When a user connects to my website and starts navigating through the menus, I want them to be redirected to a specific ...

Exploring the functionality of Radar Chart within a React component

Within the index.html file that is being utilized, there exists a javascript code specifically designed for the chart function. <script src="js/plugins/chartJs/Chart.min.js"></script> var radarData = { labels: ["In Perso ...

The PropertyOverrideConfigurer encountered an issue while processing the key 'dataSource' - The key 'dataSource' is invalid, it was expecting 'beanName.property'

During the installation of Sailpoint on Oracle, the configuration properties are as follows: ##### Data Source Properties ##### dataSource.maxWaitMillis=10000 dataSource.maxTotal=50 dataSource.minIdle=5 #dataSource.minEvictableIdleTimeMillis=300000 #dataSo ...