0

I am uploading an image via ajax and wanna instantly update them in the user profile picture element.

it works but the problem is, that the image is not moved perfectly until i refreshed the site 1-2 times.

var t = new Date().getTime(),
    avatar = $("img.user-avatar"),
    src = avatar.attr("src");
src = src.substr(0, src.indexOf("?") > 0 ? src.indexOf("?") : src.length);
avatar.attr("src", src + "?" + t);
resizeAndMoveAvatar();

the resizeAndMoveAvatar() function looks like this:

function resizeAndMoveAvatar()
{
    var Avatar = $("img.user-avatar");
    var w = Avatar.width(), h = Avatar.height();
    Avatar.css({
        'max-width': 'none',
        'max-height': 'none'
    });

    if(w > h) {
        Avatar.css('max-height', 32);
        w = Avatar.width();
        Avatar.css('left', -(w/2 - 32/2));
    }
    else if(h > w) {
        Avatar.css('max-width', 32);
        h = Avatar.height();
        Avatar.css('top', -(h/2 - 32/2));
    }
    else {
        Avatar.css({width: 32, height: 32});
    }
}

when I update it its look like this:
WRONG

but it should like this:
RIGHT

any suggestions how I can fix this problem?

thank you!

Konrad Krakowiak
  • 12,285
  • 11
  • 58
  • 45
tomew
  • 57
  • 6
  • Try using an image.onLoad event to fire your method. Have a look [here](http://stackoverflow.com/questions/5933230/javascript-image-onload) – Celt Feb 26 '15 at 09:34
  • I know what you mean, I think this will work for me – tomew Feb 26 '15 at 09:56
  • Uhm yea.. used the loadevent, definetly called but the resizing fail again. I would say it is a cache problem with FF. Same fail in Chrome and in IE and Safari it does not works completly but that is just a compatibility problem. – tomew Feb 26 '15 at 10:17
  • Yeah it could be alright. Maybe have a look into disabling the cache on that picture? – Celt Feb 26 '15 at 10:47
  • fixed the issue. I'm using now an image, that is already resized and moved into center. it works pretty well with updating it. thank you anyway :) – tomew Feb 26 '15 at 10:59
  • Nice one, could you post the code / show what you've done in the answer section for future viewers? – Celt Feb 26 '15 at 11:09

1 Answers1

0

as @Celt requested for my solution:
I update the image as before, the only change is that I don't using the resizeAndMoveAvatar function anymore because the image that I need is already resized and moved into center by a PHP-Script

works very well for me

my class: http://pastebin.com/DffcfnyC used in like this:

$Img = new Image("path/to/image.png"); // creating an instance
$Img->Square(); // center the image
$Img->Resize(32, 32); // resize it
$Img->Save("path/to/destination/image.png"); // and finally save it

love it

tomew
  • 57
  • 6