如何在不改变DPI的情况下使用java剪切图像的一部分

时间:2014-08-05 13:36:14

标签: java swing image-processing

我需要剪切使用鼠标选择的图像部分。我尝试使用Robot robot = new Robot();         BufferedImage img = robot.createScreenCapture(new Rectangle(c1,c2,w,h));

以72 dpi切割图像。我的完整源代码

  public class CropImage extends JFrame implements MouseListener,      MouseMotionListener {

int drag_status = 0, c1, c2, c3, c4;
String homedirectory = System.getProperty("user.dir");

public static void main(String args[]) {
    new CropImage().start();
}

public void start() {
    ImagePanel im = new ImagePanel(homedirectory+"/"+"images"+"/"+"6.jpg");
    add(im);
    setSize(400, 400);
    setVisible(true);
    addMouseListener(this);
    addMouseMotionListener(this);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public void draggedScreen() throws Exception {
    int w = c1 - c3;
    int h = c2 - c4;
    w = w * -1;
    h = h * -1;
    Robot robot = new Robot();
    BufferedImage img = robot.createScreenCapture(new Rectangle(c1, c2, w, h));
    File save_path = new File("screen1.jpg");
    ImageIO.write(img, "JPG", save_path);
    System.out.println("Cropped image saved successfully.");
   JOptionPane.showMessageDialog(null, "Cropped image saved successfully.");
}

@Override
public void mouseClicked(MouseEvent arg0) {
}

@Override
public void mouseEntered(MouseEvent arg0) {
}

@Override
public void mouseExited(MouseEvent arg0) {
}

@Override
public void mousePressed(MouseEvent arg0) {
    repaint();
    c1 = arg0.getX();
    c2 = arg0.getY();
}

@Override
public void mouseReleased(MouseEvent arg0) {
    repaint();
    if (drag_status == 1) {
        c3 = arg0.getX();
        c4 = arg0.getY();
        try {
            draggedScreen();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

@Override
public void mouseDragged(MouseEvent arg0) {
    repaint();
    drag_status = 1;
    c3 = arg0.getX();
    c4 = arg0.getY();
}

@Override
public void mouseMoved(MouseEvent arg0) {
}

public void paint(Graphics g) {
    super.paint(g);
    int w = c1 - c3;
    int h = c2 - c4;
    w = w * -1;
    h = h * -1;
    if (w < 0) {
        w = w * -1;
    }
    g.drawRect(c1, c2, w, h);
}

}

类ImagePanel扩展了JPanel {

private Image img;

public ImagePanel(String img) {
       this(new ImageIcon(img).getImage());
}

public ImagePanel(Image img) {
    this.img = img;
    Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
    // Dimension size = new Dimension(10,10);
    setPreferredSize(size); setMinimumSize(size);
    setMaximumSize(size); setSize(size); setLayout(null);
}

public void paintComponent(Graphics g)
{
    g.drawImage(img, 0, 0, null);
}

}

我需要以300 dpi裁剪所选部分作为打印就绪图像。有任何想法请建议。

1 个答案:

答案 0 :(得分:1)

resample所示,您需要300 / 72d使用AffineTransform AffineTransformOp.TYPE_BICUBIC因素here。正如interpolating一样,为interpolationType指定质量较高的{{1}},即使速度较慢。更新图片的元数据,如here所示。