0

I am new here so please bear with me! I have used another script I found on SO where a small 50 pixel thumbnail image is displayed in the browser after a user selects the browse button and chooses an image.

The HTML of the form look like:

<input type='file' onchange="readURL(this);" />
<img id="blah" src="http://openglobaldirectory.com/images/default_profile.gif" width="50" alt="your image" />

And I have a JavaScript function that looks like:

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#blah')
                .attr('src', e.target.result)
                .width(50)
                .height(50);
        };
        reader.readAsDataURL(input.files[0]);
    }
}

When the user selects the image from the file the 50x50px thumbnail displays in the page however, it will compress the whole image and unless the image selected is a square (or almost square) the thumbnail generated looks very distorted.

What I would like to do is create a cleaner thumbnail that will not display a distorted or compressed image, regardless of the size of the original. I suppose what will need to happen is to first bring the height of the image down to 50px and then take thumbnail based on the 50px worth of image in the middle.

Does anyone know a way to do this?

Btw the original script I am following as an example can be found here: HTML - Display image after selecting filename

Community
  • 1
  • 1
  • would setting just the width to 50px work.... the height will automatically adjust – tyler Oct 30 '13 at 01:32
  • If not look at this link http://stackoverflow.com/questions/493296/css-display-an-image-resized-and-cropped – tyler Oct 30 '13 at 01:34

1 Answers1

0

If you know that all your images are being "downsized" (ie. they all have at least one dimension greater than 50px), you could remove the width attribute in the img tag and put this inside the img tag:

style='max-width:50px; max-height:50px;'

If you want to cover all cases, you can modify your javascript so that it sets the image size to be larger if it needs to be larger to fill out your thumbnail space.

function readURL(input) {

    var imageSize = 50;

    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {

            var blah = $('#blah');
            blah.attr('src', e.target.result);

            var height = blah.height();
            var width = blah.width();

            if (height < imageSize && width < imageSize) {
                if (width > height) {
                    blah.width(imageSize);
                }
                else {
                    blah.height(imageSize)
                }
            }
        };
        reader.readAsDataURL(input.files[0]);
    }
}
Scampbell
  • 1,384
  • 12
  • 22