Search code examples
javascriptimagejspuploadresize-image

Image resizing giving error(srcImg.attr)is not a function?


Here i'm uploading image and in text boxes giving new width and height when i submit original image size has to change according to new width and height and save in same folder.But it is not working how can i do this,anybody help me please?

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Demo</title>
    <script>
        function ImageResizer() {
            var srcImg = document.getElementById("imgID").value;
            var newImg = new Image();
            newImg.src = srcImg.attr('src');
            var height = newImg.height;
            var width = newImg.width;
            var newWidth = document.getElementById("widthID").value;
            var newHeight = document.getElementById("HeightID").value;               
        }
    </script>
</head>
<body>
    <%
        out.println("<table>");
        out.println("<tr><td><input type='file' id='imgID'></td></tr>");
        out.println("<tr><td>Enter new Width:</td><td><input type='text' id='widthID'></td></tr>");
        out.println("<tr><td>Enter new Height:</td><td><input type='text' id='HeightID'></td></tr>");
        out.println("<tr><td><input type='button' value='Submit' onclick='ImageResizer()'></td></tr>");
        out.println("</table>");
    %>
</body>

This is my demo.jsp page,where i'm uploading image and want to resize the uploaded image with new height and width.


Solution

  • That's because srcImg contains the value of input but not the input itself. You're trying to access the attr of a value which will always be undefined . Instead just use

    newImg.src = srcImg; // srcImg itself contains the value of input
    

    If you want the input then use:

    var srcImg = document.getElementById("imgID");
    

    Modified your js function:

    function ImageResizer() {
        console.log('called');
        var srcImg = document.getElementById("imgID").value;
        var newImg = new Image();
        newImg.src = srcImg;
        var height = newImg.height;
        var width = newImg.width;
        var newWidth = document.getElementById("widthID").value;
        var newHeight = document.getElementById("HeightID").value;
        console.log(newImg, srcImg, newWidth, newHeight, height, width);
    }
    

    Demo: http://jsfiddle.net/lotusgodkk/GCu2D/182/