如何使用java保存文件夹中的调整大小?

时间:2015-05-06 15:38:28

标签: java path resize

任何人都可以帮我如何将调整大小图像保存在文件夹中吗?我正在使用bufferedimage和jfilechooser。请各位帮助我。

private void cmd_attachActionPerformed(java.awt.event.ActionEvent evt) {                                           
        JFileChooser ch = new JFileChooser();
        ch.showOpenDialog(null);
        File f=ch.getSelectedFile();
        filename =f.getAbsolutePath();
        path.setText(filename);
        try{
            File image = new File(filename);
            BufferedImage bufferedimage=ImageIO.read(image);
            BufferedImage thumbnail=Thumbnails.of(bufferedimage)
            .size(150,188)
            .asBufferedImage();

            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(thumbnail, "jpeg", os);

            InputStream is=new ByteArrayInputStream(os.toByteArray());
            // FileInputStream fis=new FileInputStream(image);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];

            try{
                for (int readNum; (readNum=is.read(buff ))!=-1;){
                    bos.write(buff,0,readNum);
                    System.out.println("Read" +readNum+ "bytes,");
                }
            }catch(IOException ex){
                java.util.logging.Logger.getLogger(Employee_info.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            person_name=bos.toByteArray();
        }catch(Exception e){

            JOptionPane.showMessageDialog(null, "Select an image!");
        }
        finally{
            try{
                pst.close();
                rs.close();
            }catch(Exception e){
            }
        }
        Update_table();
    }       

1 个答案:

答案 0 :(得分:0)

如果您已经BufferedImage,则可以使用Graphics2D

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();

AffineTransformation缩放图片

/**
 * scale image
 * 
 * @param image to scale
 * @param type type of image
 * @param dWidth width of destination image
 * @param dHeight height of destination image
 * @param fWidth x-factor for transformation / scaling
 * @param fHeight y-factor for transformation / scaling
 * @return scaled image
 */
public static BufferedImage scale(BufferedImage image, int type, int dWidth, int dHeight, double fWidth, double fHeight) {
    BufferedImage dbi = null;
    if(image != null) {
        dbi = new BufferedImage(dWidth, dHeight, type);
        Graphics2D g = dbi.createGraphics();
        AffineTransform at = AffineTransform.getScaleInstance(fWidth, fHeight);
        g.drawRenderedImage(image , at);
    }
    return dbi;
}