Stuntman – Open source STUN server
I’ve been trying to write this blog for for way too long now. So I’ll just keep it brief and save the essay portion for later.
A few weeks ago, I posted a new revision of my open source STUN server code, now called Stuntman, to Github. I followed this up with a mirror of the code on Sourceforge. And finally, a website for the project itself. The latter, I hope to expand into a resource section on NAT traversal and P2P.The new version extends the previous UDP server functionality with corresponding support for TCP (including both IPv4 and IPv6). Also, lots of code cleanup and ported to more Unix platforms besides Linux (MacOS Lion, Solaris, BSD, etc….)
It was really run writing a non-blocking asynchronous TCP server, getting reacquainted with sockets, and making it all run fast. That, and it’s just 1 SMOP away from supporting a multi-threaded mode.
For a future release, I am strongly considering supporting the full-mode of the STUN to allow for the two IP addresses of the service to work across two different hosts as opposed to requiring a host to have more than one IP address. This would allow Stuntman to run on Amazon EC2 in its full configuration mode. But then, I as I glance at the W3C logs for stunprotocol.org, I see the majority of lot of entries with peculiar attributes. Most notably a pattern in the user-agent strings such as the following:
“Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1″
Hmmm…. I think the visitors to my site are trying to tell me something about an operating system they would like to see support for. It was always the intent, I just need to find the time.
Scale, crop, and center an image with correct aspect ratio in HTML and Javascript
Summary
In this post, I’ll show a technique using HTML and Javascript to properly scale an image of indeterminate size to take up the full space of a parent element that may have a different size, aspect ratio, and orientation. This technique is useful for such scenarios as dynamically generating thumbnails and for displaying a “table of images” where every image is the same size (but the source images aren’t).
Background
In development of my HTML image gallery control, I re-encountered a problem I’ve had with image and video applications. In such applications, the size of the source image (or video) may differ from the size of the target surface it is rendered on. Additionally, the aspect ratio between the source image and target surface may be drastically different. (And in such cases, the image sizes may not be known at design time). The source image may be have a portrait orientation and the surface have a landscape orientation (or vice versa). The user can resize the window and have the content rescale and realign appropriately. Additionally, the view for such content may be to just scale and center it with “bars”. Or the desired view may be to crop the center section out of the image and scale it to fit the entire surface. I’ve seen plenty of image manipulation code bases with implementations of a “compute resize” function incorrectly written. Such implementations often assume the original and desired image size are both landscape orientations. There’s usually edge case bugs with portrait mode and going between various sizes.
What this post is not about.
- This is not another post about “how to center an image within a div”. In those cases, you likely have an image of fixed size to be centered positioned within a larger div.
- If your HTML scenario includes having complete control of the image size, or you know the image size at design time, this post may not be for you.
In both of these cases, go use your favorite image editing tool, and standard CSS to correctly scale and center the image in the DOM using static markup. I’ll cover some static scenarios briefly below to built up to the discussion on a scriptable way to do this for dynamic content.
Simple scenario – static content
Let’s start with a how a web designer or web developer might do something like this with static markup and local content.
Imagine we want to generate a square thumbnail (150×150) of an existing image. But the image is of a different size – in this case: 300×200. We also want a dark gray border on the thumbnail. The HTML markup may look something like the following to start. (For brevity and readability, I am deliberately in-lining the “style” attribute instead of using a style-sheet.).
<div style="width: 150px; height: 150px; border: thick solid #666666;">
<img src="tanahlot.jpg" />
</div>
The result will look something like the following:
The image is too big for the div it is hosted in. The obvious thing to do would be to set the width and height attributes to 150px on the image to force it into a square area. This will lead to a distorted image because the image itself is not originally square. To maintain the aspect ratio, the right thing to do is set the width or height, but not both, to be 150px. But which dimension do you set? If you set the width to 150px, the height automatically gets scaled to 100px. This will leave 50 pixels of empty space underneath the image. It won’t be centered. If you set height to 150px and leave the width attribute unset, then width gets automatically scaled to 225px. This will render a viewable thumbnail that takes up the entire space, but it won’t be centered either. The resulting thumbnail will be just a view of the top-left area of the image. We likely would want to have the center area be visible.
We’re going to need to do a few things to get this right.
- Adjust the width and height attributes of the image such that it maintains its aspect ratio and fits within 150x15o area. The original aspect ratio of the image is 300:200 (or 1.5). In this case, if height is fitted to be 150, then width would (150*1.5) == 225px.
- Use absolute positioning to center the image. If we scaled the dimensions of the image from 300×200 to 225×150, then we need to move the image to the left by[(image width – div width)/2] == [(225-150)/2] == 37 pixels.
- Set the overflow style on the parent div to “hidden” so that the extra portion of the image that that doesn’t fit gets cropped away.
The final adjustments looks like the following:
<div style="width: 150px; height: 150px; border: thick solid #666666; overflow: hidden; position: relative;">
<img src="tanahlot.jpg" style="position: absolute; left:-37px; width:225px; height: 150px;"/>
</div>
Perfectly scaled, cropped, and centered to generate a thumbnail of the original image. The combination of a negative left offset to position the image and use of the overflow:hidden style allow the iamge to be sized larger than the parent element, but cropped appropriately.
Alternatively, the width of the image can be fitted and the height scaled to match. Then center vertically instead of horizontally to create a “letterbox” look.
<div style="width: 150px; height: 150px; border: thick solid #666666; overflow: hidden; position: relative;">
<img src="tanahlot.jpg" style="position: absolute; top:25px; width:150px; height: 100px;"/>
</div>
The letterbox result looks like this:
Scaling, cropping, and centering when you don’t know the dimensions of the image (until it has been downloaded).
Now let’s discuss how to do a proper scaling when the dimensions of the image are unknown until page load time. Such is the case when showing images delivered by an online photo service. The service may return images at various sizes, aspect ratios, and orientation. But the expectation is that the image is rendered at the same size on the page.
First, one decision has to be made up front: Fitted or Zoomed?
- Fitted (“Letterboxed”) – the entire image is scaled such that both the width and height of the source fit within the parent. The entire image is visible with no cropping. The letterboxed image is centered within the parent. Empty space (“black bars”) may take up any remaining space. (Similar to watching a widescreen DVD movie on a standard definition TV.)
- Zoomed (“Pan&Scan”) – The image is scaled proportionally such that only one dimension (width or height) fits within the parent DOM element. The other dimension extends outside the boundary of the surface.
While “letterbox” is appropriate for DVDs, I suggest the “zoomed” mode for most scenarios. Especially for thumbnail creation or when you have a need to make all images look uniform regardless of original dimensions.
Solution
Let me present a worthy helper function that forms the basis for our solution.
function ScaleImage(srcwidth, srcheight, targetwidth, targetheight, fLetterBox) {
var result = { width: 0, height: 0, fScaleToTargetWidth: true };
if ((srcwidth <= 0) || (srcheight <= 0) || (targetwidth <= 0) || (targetheight <= 0)) {
return result;
}
// scale to the target width
var scaleX1 = targetwidth;
var scaleY1 = (srcheight * targetwidth) / srcwidth;
// scale to the target height
var scaleX2 = (srcwidth * targetheight) / srcheight;
var scaleY2 = targetheight;
// now figure out which one we should use
var fScaleOnWidth = (scaleX2 > targetwidth);
if (fScaleOnWidth) {
fScaleOnWidth = fLetterBox;
}
else {
fScaleOnWidth = !fLetterBox;
}
if (fScaleOnWidth) {
result.width = Math.floor(scaleX1);
result.height = Math.floor(scaleY1);
result.fScaleToTargetWidth = true;
}
else {
result.width = Math.floor(scaleX2);
result.height = Math.floor(scaleY2);
result.fScaleToTargetWidth = false;
}
result.targetleft = Math.floor((targetwidth - result.width) / 2);
result.targettop = Math.floor((targetheight - result.height) / 2);
return result;
}
The function above takes 5 parameters:
- srcwidth – integer width of the source image that we want to scale
- srcheight – integer height of the source image that we want to scale.
- targetwidth – integer width of the parent element that we want to fit the image into
- targetheight – integer height of the parent element that we want to fit the image into
- fLetterBox – True if we want the “fitted” mode. Otherwise, the function uses the “zoom” mode.
The function above returns an object with the following properties defined:
- width – new width that should be applied to the image for scaling
- height – new height that should be applied to the image for scaling
- targetleft – What the left position attribute of the image should be (can be negative)
- targettop – What the top position attribute of the image should be (can be negative)
- fScaleToTargetWidth – bool indicating which dimension was clamped down to fit exactly the size of the parent. (The other dimension was set to keep the aspect ratio correct).
The function above does the math to decide how to scale the image to fit within (or across) a specified area. It does not matter if the image or target are in portrait or landscape orientations. The code above will return the correct result. It also doesn’t matter if the image is “scaling down” (the common case for thumbnails) or “scaling up” for images smaller than it’s parent. The image will fill the parent. (It would be trivial to modify the ScaleImage function above to have a “not grow” mode.
Now let’s wrap this solution up. The only thing to do is to attach an event handler to the “onload” event of the image to call ScaleImage and apply the result to the DOM objects. Let’ use one additional helper function to do the work of calling ScaleImage and applying the result. For brevity, we’ll use JQuery calls to get and set many of the properties and css attributes related to size and offset.
function OnImageLoad(evt) {
var img = evt.currentTarget;
// what's the size of this image and it's parent
var w = $(img).width();
var h = $(img).height();
var tw = $(img).parent().width();
var th = $(img).parent().height();
// compute the new size and offsets
var result = ScaleImage(w, h, tw, th, false);
// adjust the image coordinates and size
img.width = result.width;
img.height = result.height;
$(img).css("left", result.targetleft);
$(img).css("top", result.targettop);
}
We still need the parent element to still have position:relative and overflow:hidden as part of its CSS styling. The image element itself need only have the position:absolute tag applied to it. Again, for brevity, I’ll set the onload event callback directly within the markup.
<div style="width: 150px; height: 150px; border: thick solid #666666; overflow: hidden; position: relative;">
<img src="tanahlog.jpg" style="position: absolute;" onload="OnImageLoad(event);"/>
</div>
And we’re done. When the page loads, the image downloads and gets instantly scaled to fit.
Visit the sample page at http://www.selbie.com/playground/aspectcorrect/aspectcorrect.htm to see variations of image scaling across different source and target sizes.


