Alex Cane
Alex Cane

Reputation: 167

Verify image size

Alright so here it goes, I have my user system working perfectly, and now in the edit profile, I'm trying to add a change avatar URL option.

At the moment it's working great, but for pageloads time and such, I'm looking to restrain the normal users to a maximum of 300px images width, and let's say around 500px height, that are then resized in

So basically, I just want a javascript function to verify the URL of an image (entered in a textbox) and if it is over the size I want, well the user gets an alert saying remote image too big & the process ends there.

I tried several ways, but I never got to my goal, so any help would be greatly appreciated!

tl;dr : User input image in text box > click submit button > if image is over size i definite > alert & end process

Thank you!

Upvotes: 2

Views: 5230

Answers (3)

esamatti
esamatti

Reputation: 18944

Just create a new Image object with that url and check its width and height attributes after the onload event.

var img = new Image();
img.onload = function(){
   alert(img.width);
};
img.src = "http://example.com/avatar.png";

There is no need for server-side with this, but you should note that users are able to override this since it's done solely on the browser.

Upvotes: 2

fcalderan
fcalderan

Reputation:

this kind of control has to be done on server-side. Javascript should not be used to get image size before form submitting.

If image is too big just discard the image and returns an error message to the user

Upvotes: 0

Pointy
Pointy

Reputation: 413682

I think this is something you should do with your server-side code. Have the page submit the form, the server can fetch it and check the size, and then the server should return an error if the image is too big.

Upvotes: 0

Related Questions