1

I have an asp.net mvc project, and a function that streams out an image based on url parameters. like: /Image/40/100/50 streams out image with ImageID 40, 100px wide and 50px high.

So is there a way to change:

<img class="image" src="/Content/View?fileID=31" style="width: 500px; height: 100px; " />

To:

<img class="image" src="/Image/31/500/100" style="width: 500px; height: 100px; " /> 

In some fancy way? /Lasse

1
  • Be certain that the browser will load the original image in every case! So if you want to scale the images to save bandwidth, this is not the right way. Commented Dec 29, 2011 at 15:11

2 Answers 2

3

I'm not sure I understand why you're trying to do this, but something along the lines of the following should do the trick:

$("img[src^='/Content/View?fileID=']").each(function() {
    var img = $(this);
    var id = img.attr("src").substring(21);
    img.attr("src", "/Image/" + id + "/" + img.width().toString() + "/" + img.height().toString());
});

Link to example: http://jsfiddle.net/Cfdfp/2/

Also, if you're only applying the image class to img elements that require this transformation, you could simplify the selector above:

$(".image").each(function() {
    var img = $(this);
    var id = img.attr("src").substring(21);
    img.attr("src", "/Image/" + id + "/" + img.width().toString() + "/" + img.height().toString());
});

Link to example: http://jsfiddle.net/Cfdfp/1/

Sign up to request clarification or add additional context in comments.

Comments

1

How about this:

$('img').each(function() {
    var $this = $(this),
        id = $this.attr('src').substr($this.attr('src').indexOf('=')+1),
        wid = $this.width(),
        hgt = $this.height();
    $this.attr('src','/Image/'+id+'/'+wid+'/'+hgt);
});

1 Comment

Why using $this.attr('width') instead of $this.width()? He wants to respect the css width value, not the attribute width.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.