0

I need to know how i can scale the uploaded images and save it on the server in the Upload folder.

I have this to process the the form where people can upload there files.

public void init() {
    fileSavePath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;/*save uploaded files to a 'Upload' directory in the web app*/
    if (!(new File(fileSavePath)).exists()) {
        (new File(fileSavePath)).mkdir();    // creates the directory if it does not exist        
    }
}


public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {


        String resp = "";
        int i = 1;
        resp += "<br>Here is information about uploaded files.<br>";
        try {
            MultipartParser parser = new MultipartParser(request, 1024 * 1024 * 1024);  /* file limit size of 1GB*/
            Part _part;
            while ((_part = parser.readNextPart()) != null) {
                if (_part.isFile()) {
                    FilePart fPart = (FilePart) _part;  // get some info about the file
                    String name = fPart.getFileName();
                    if (name != null) {
                        long fileSize = fPart.writeTo(new File(fileSavePath));
                        resp += i++ + ". " + fPart.getFilePath() + "[" + fileSize / 1024 + " KB]<br>";
                    } else {
                        resp = "<br>The user did not upload a file for this part.";
                    }
                }
            }// end while 
        } catch (java.io.IOException ioe) {
            resp = ioe.getMessage();
        }
        request.setAttribute("message", resp);
        getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
    }

For example i need to rezise all the image to 100x100

1 Answer 1

0

First save it, then load it, then scale, then resave it.

try 
{
    BufferedImage img = ImageIO.read(new File(in_path));
    Image scaled = img.getScaledInstance(100, 100, Image.SCALE_FAST);
    ImageIO.write(scaled, "png", out_path);
}
catch (Exception ex)
{
    System.out.println(ex.getMessage();
}

See http://docs.oracle.com/javase/7/docs/api/java/awt/Image.html for list of scaling methods that can be used in the third parameter of getScaledInstance

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.