Tips for Limiting Upload Image Size with Maximum Width and Height

Is it possible to set a maximum width and height for an image before uploading it? I want the user to select a file, see a preview of the image, crop it, and then upload it to be saved in a directory. How can I enforce a max width and height limit before allowing the user to preview the selected image?

If the image exceeds the specified max height and width, display a message asking for a smaller picture.

HTML CODE:

<img id="uploadPreview" style="display:none;" />

<!-- Image uploading form -->
<form action="upload.php" method="post" enctype="multipart/form-data">
<input id="uploadImage" type="file" accept="image/jpeg" name="image" />
<input type="submit" value="Upload" />

<!-- Hidden inputs -->
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
</form>

JQUERY CODE:

function setInfo(i, e) {
    $('#x').val(e.x1);
    $('#y').val(e.y1);
    $('#w').val(e.width);
    $('#h').val(e.height);
}

$(document).ready(function() {
    var p = $("#uploadPreview");

    // Prepare instant preview
    $("#uploadImage").change(function(){
        // Fade out or hide preview
        p.fadeOut();

        // Prepare HTML5 FileReader
        var oFReader = new FileReader();
        oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);

        oFReader.onload = function (oFREvent) {
            p.attr('src', oFREvent.target.result).fadeIn();
        };
    });

    // Implement imgAreaSelect plugin (http://odyniec.net/projects/imgareaselect/)
    $('img#uploadPreview').imgAreaSelect({
        // Set crop ratio (optional)
        aspectRatio: '1:1',
        onSelectEnd: setInfo
    });
});

Answer №1

Here is the section that requires modification

aspectRatio: '1:1',

To experiment, change it to aspectRatio: '1:1.3',

You'll notice a difference in the cropping area ratio

Answer №2

Have you implemented Jcrop for cropping the image? If so, they have included parameters to restrict the maxWidth and maxHeight.

If you are utilizing a custom div that overlaps the previewed image as a cropped area, then specify the maxwidth and maxheight for that div.

For example:

setSelect: [ 50, 50, 274, 196 ],
                maxSize: [224, 146],
                minSize: [224, 146],

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

Navigating a Bootstrap modal using arrow keys for scrolling - up and down

I attempted to address this issue by using the following code: // here, 'this' represents the modal $(this).focus(); Despite trying the above solution and even attempting to trigger a click event on it, I was unable to get it to work! UPDATE ...

Ways to establish whether the element $(this) is present in an array during a click event

I am currently working on populating 4 arrays with a set of id values. Each array will eventually be assigned text values for an h1 and a p element, but for now I am focusing on setting up an alert when one of the images in the array named graphicDesign is ...

Converting a multi-dimensional array to a single array in JavaScript: the ultimate guide!

I have encountered a scenario in my application where there is an array with multiple arrays nested inside: https://i.sstatic.net/3uHP9.png I am looking to transform this structure: [ { "tag": [ { "key": "asda ...

Tips on incorporating a firebase object into your Angular application using $scope

As a beginner in coding, I would greatly appreciate a simple answer. I am attempting to treat a Firebase object as a JavaScript array for use in HTML via $scope. What is the most effective approach? Database: database Current code: var mainApp = angula ...

Eliminating the dependency on Angular $http in a custom JavaScript library

Is there a way to develop a versatile JavaScript library that can be utilized across different frameworks, while still being able to leverage Angular's $http service when necessary? Would it be feasible to incorporate jQuery as a fallback for other fr ...

Retrieve the current day's value from an array

I have a list of days with corresponding opening and closing hours, now I need to find the operating hours for today. For instance, if it's Friday, then the current hours should be "11:30 AM – 9:30 PM". How can I achieve this using JavaScript? ["Mo ...

Switch out feature within prototype attribute looping

I'm attempting to substitute all hyphens in attributes with underscores. <a href="/page" id="someId" data-country="north-america" data-state="north-dakota">North Dakota</a> This is the code snippet I am using: var el = document.getEleme ...

A step-by-step guide on showcasing Flickr images through API using a Justified Gallery

I am looking to integrate the Miromannino Justified Gallery () into my project, but I want it to showcase images fetched from Flickr. I have successfully implemented the code to retrieve photos from Flickr using the API through Ajax: $.ajax({ url ...

Vue.js: Conditionally preventing form submission

Currently, I am implementing form validation using VeeValidate. Although I prefer not to rely on JavaScript for form submission, I still want to prevent users from submitting the form if there are any errors present. However, using the code snippet below s ...

How can we utilize CSS floats to achieve maximum widths?

I currently have 5 divs that I need to structure in a specific way: Each div must have a minimum size of 100px The parent container should display as many divs as possible on the first row, with any remaining divs wrapping to new rows if necessary If the ...

utilizing object methods to retrieve object attributes

I am currently working on developing a new application named myApp. This application includes a property called regularNameErrors and a method called populateJSON. The populateJSON method utilizes an AJAX call to retrieve a JSON object, which is then added ...

Unable to determine the reason behind the code getting stuck in an endless loop

Check out this code snippet: import React from 'react'; import Card from './components/Card'; import './App.css'; import Buttongrp from './components/Buttongrp'; import { useEffect, useState } from 'react'; ...

Modifying two distinct charts according to the choices made in two independent dropdown menus

In my current project, I am facing a challenge with integrating two separate dropdowns containing UFC fighter names. The goal is to display a plot showing the KD (Knockdown) data for the selected fighters over time when their names are chosen from both dro ...

Tips for displaying the node's label in Arbor js when hovering over the node

I'm currently utilizing Arbor Javascript to exhibit a graph composed of nodes and edges. My objective is to have the node's label displayed when the mouse hovers over it within the graph. Below is the code snippet I am working with: <canvas i ...

"A lengthy contenteditable div designed to mimic an input field, with the ability to horizontally scroll

When the input is too short for the entire text to be displayed, users have the option to horizontally scroll the text inside the input by dragging with the mouse. Is there a way to implement this functionality in a contenteditable field that appears as ...

Intersection Observer is functioning properly as elements vanish once they finish appearing

New to this forum and looking forward to receiving assistance and making some fantastic connections! Currently working on my personal portfolio with the goal of getting it online for job hunting purposes, but encountering some challenges along the way. T ...

The endpoint /api/user does not allow POST requests

I'm currently testing a user registration route and encountering a "Cannot POST /api/user" error. Although I can successfully make a GET request using Postman, the issue arises when trying to make a POST request. Any help or guidance on pinpointing t ...

The date in the JSON response does not align correctly

Seeking insights into this issue, I am currently utilizing the code below to generate a JSON response through an AJAX request console.log('get_therapist_sessions', response); response.forEach(function(item){ console.log(item); ...

"Encountering an error while attempting to map a JSON array in

I am just starting to work with knockoutjs and I'm attempting to map JSON data to KO. Here is my code: My goal is to parse the JSON data and display it in a table. However, when I try to use ko.compute, I encounter an error saying "self.firstName() i ...

What is the best way to monitor React hooks efficiently?

Prior to diving into a new React project, I always make sure that there are adequate developer tools available for support. One of my favorite features in React is the React Developer tool for Google Chrome. It allows me to examine the internal state of e ...