if
(w<
0
)
if
(w<
0
)
59 |
w = w * - 1 ; |
60 |
g.drawRect(c1, c2, w, h); |
61 |
62 |
} |
说明:
下面是 draggedscreen 方法的代码
Listing 4: draggedScreen 方法
01 |
public void draggedScreen() throws Exception |
02 |
{ |
03 |
int w = c1 - c3; |
04 |
int h = c2 - c4; |
05 |
w = w * - 1 ; |
06 |
h = h * - 1 ; |
07 |
Robot robot = new Robot(); |
08 |
BufferedImage img = robot.createScreenCapture( new Rectangle(c1, c2,w,h)); |
09 |
File save_path= new File( "screen1.jpg" ); |
10 |
ImageIO.write(img, "JPG" , save_path); |
11 |
System.out.println( "Cropped image saved successfully." ); |
12 |
}} |
说明:
Listing 5: ImagePanel.java
01 |
import java.awt.Dimension; |
02 |
import java.awt.Graphics; |
03 |
import java.awt.Image; |
04 |
05 |
import javax.swing.ImageIcon; |
06 |
import javax.swing.JPanel; |
07 |
08 |
class ImagePanel extends JPanel { |
09 |
10 |
private Image img; |
11 |
12 |
public ImagePanel(String img) { |
13 |
this ( new ImageIcon(img).getImage()); |
14 |
} |
15 |
16 |
public ImagePanel(Image img) { |
17 |
this .img = img; |
18 |
Dimension size = new Dimension(img.getWidth( null ), img.getHeight( null )); |
19 |
// Dimension size = new Dimension(10,10); |
20 |
setPreferredSize(size); |
21 |
setMinimumSize(size); |
22 |
setMaximumSize(size); |
23 |
setSize(size); |
24 |
setLayout( null ); |
25 |
} |
26 |
27 |
public void paintComponent(Graphics g) { |
28 |
g.drawImage(img, 0 , 0 , null ); |
29 |
} |
30 |
31 |
} |
Listing 6:CropImage.java
001 |
import java.awt.Graphics; |
002 |
import java.awt.Rectangle; |
003 |
import java.awt.Robot; |
004 |
import java.awt.event.MouseEvent; |
005 |
import java.awt.event.MouseListener; |
006 |
import java.awt.event.MouseMotionListener; |
007 |
import java.awt.image.BufferedImage; |
008 |
import java.io.File; |
009 |
import javax.imageio.ImageIO; |
010 |
import javax.swing.JFrame; |
011 |
012 |
public class CropImage extends JFrame implements MouseListener, MouseMotionListener |
013 |
{ |
014 |
int drag_status= 0 ,c1,c2,c3,c4; |
015 |
public static void main(String args[]) |
016 |
{ |
017 |
new CropImage().start(); |
018 |
} |
019 |
public void start() |
020 |
{ |
021 |
ImagePanel im= new ImagePanel( "F:\\Wallpaper\\wallpapers\\1.jpg" ); |
022 |
add(im); |
023 |
setSize( 400 , 400 ); |
024 |
setVisible( true ); |
025 |
addMouseListener( this ); |
026 |
addMouseMotionListener( this ); |
027 |
setDefaultCloseOperation(EXIT_ON_CLOSE); |
028 |
} |
029 |
public void draggedScreen() throws Exception |
030 |
{ |
031 |
int w = c1 - c3; |
032 |
int h = c2 - c4; |
033 |
w = w * - 1 ; |