bill-bigmojo
-
1/8/2009 8:23:39 PM
Aspect Ratio Respecting Image Resizing
So,
Using the image gallery widget and what not, I was pretty perturbed to see that there is no function to pass in a width/height AND respect aspect ratio, something that you basically need always.
The issue here is that not all images are 3:4, some are very tall, some very long, but i still need them to fit in my box both width and height wise.
Originally I thought I could write a function that would take the guid, and get me the height/width, I could do some math and return the desired 'maxsidesize' or what have you.. but there are no methods to do this without versionid and a datasource.
I eventually tracked down the CMSPages/getfile.aspx.cx code, it is called every time an image request is made, and has the resizing logic. Funnily enough they implemented an aspect ratio respecting method, but it doesn't get called ever..
So I created this method (which is no magic) --- private void MaintainAspect(int pictureWidth, int pictureHeight) { if (this.Height == 0 || this.Width == 0) { this.SetRate(pictureWidth, pictureHeight); return; } float desiredRatio = this.Width / this.Height; ; float origRatio= (float)pictureWidth / (float)pictureHeight;
if (origRatio > desiredRatio) { //set height this.Height = (int)(((float)this.Width) / origRatio); }else{
this.Width = (int)(((float)this.Height) * origRatio); } } -------------
Drop that into CMSPages/getfile.aspx.cx and call it inside the 'protected void ProcessFile(Guid attachmentGuid)' method, put it right before this line outputFile = new CMSOutputFile(atInfo, null); which in my code is line 609. Essentially you set your 'this.height' and 'this.width' before it builds the output file, and it will resize the image.
//maintain aspect ratio this.MaintainAspect(atInfo.AttachmentImageWidth, atInfo.AttachmentImageHeight); //end ratio
Sorry about the lack of formatting, Hope that helps someone.
|