Friday, August 9, 2013

Java Image Upload with Crop And Bolb Creation

private void jButton_Image_UploadActionPerformed(java.awt.event.ActionEvent evt) {                                                    
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog(null);
        File f = chooser.getSelectedFile();

        filename = f.getAbsolutePath();

        String fileName1 = f.getName();
        String filePath = filename.substring(0, filename.lastIndexOf(File.separator));

        //  JOptionPane.showMessageDialog(null, filePath);
        JOptionPane.showMessageDialog(null, fileName1);

        jTextField_Path.setText(filename);
        //JOptionPane.showMessageDialog(null, filename);

        try {
            imagex = new File(filename);
            fis = new FileInputStream(imagex);

            // image scale down method

            BufferedImage originalImage = ImageIO.read(new File(filename));//change path to where file is located
            int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();

            BufferedImage resizeImageJpg = resizeImage(originalImage, type, 100, 100);
            ImageIO.write(resizeImageJpg, "jpg", new File("d:\\test\\Dcl" + fileName1));

            // image scale down method

            // send to DB start
            image2 = new File("d:\\test\\Dcl" + fileName1);
            inputStream = new FileInputStream(image2);
            // send to DB End


            //  JOptionPane.showMessageDialog(null, os);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum);

            }
            upload_image = bos.toByteArray();
            // view uploaded image
            ImageIcon tinyPicture = new ImageIcon(upload_image);
            Image imagexx = tinyPicture.getImage();
            //  JOptionPane.showMessageDialog(null, imagexx);
            imagexx = imagexx.getScaledInstance(105, -1, imagexx.SCALE_SMOOTH);
            tinyPicture.setImage(imagexx);
            jLabel_Image.setIcon(tinyPicture);

        } catch (Exception e) {
            System.out.println("Exception Occured:" + e);
        }
    }             

   private static BufferedImage resizeImage(BufferedImage originalImage, int type, int IMG_WIDTH, int IMG_HEIGHT) {
                        BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
                        Graphics2D g = resizedImage.createGraphics();
                        g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
                        g.dispose();

                        return resizedImage;
        }                                     

No comments:

Post a Comment