简体   繁体   中英

How to change the size of image with given new height and width using java?

This is my demo.jsp page where i have two fields to give new height and width to change the uploaded image size with new one.could anybody tell me how to do this?

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>ImageSizeModification</title>
    <script>
        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);
        }
    </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>

If I understand correctly, what you want to do is to resize an image in the browser, so a smaller file goes up to your server. If that's so, this is not a Java/JSP question, but a Javascript one.

This post discusses how to do that using javascript libraries, and I think might solve your problem.

document.getElementById("imgID").style.height =  parseInt(newWidth) ;
document.getElementById("imgID").style.width =  parseInt(newHeight) ;

add above two line before console log.

or using Jquery

$('#imgID').width(700); 
$('#imgID').height(700);

You cannot do it with jsp alone you need to create a servlet get the image through Inputstream manipulate it through any image manipulation api and write it to response. Imgscalr is an easy to use api. You can refer this link example and clarification

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM