Search code examples
javascriptcssimageaspect-ratiojcrop

maintaining aspect ratio


I am working on an image cropping tool at the moment, the image crop tool comes from jCrop, what I am trying to is make the image the user takes the crop from smaller than the original uploaded. Basically if uploads a landscape image I need to make the image 304px wide without alterting the aspect ratio of the shot.

For instance if the user uploads a portrait shot, I need make the image 237px without altering the aspect ratio of the shot.

Is this possible? I have access to original images sizes in my code, but I cannot work out make sure I am not altering the aspect ratio?


Solution

  • Yes, it's possible if the source image is already wide enough. If it's not wide enough there isn't enough data to crop and if you wanted to maintain aspect ratio, you'd need to scale the image up before the crop.

    Something like this should get you started:

    CropWidth=237;
    AspectRatio= SourceWidth/SourceHeight; 
    CropHeight = CropWidth*AspectRatio;