当前页面: 开发资料首页 → Java 专题 → 编写一个基于Java Robot类的屏幕捕获工具
摘要: 编写一个基于Java Robot类的屏幕捕获工具
// Hide Capture's main window so that it does not appear in
// the screen capture.
setVisible (false);
// Perform the screen capture.
BufferedImage biScreen;
biScreen = robot.createScreenCapture (rectScreenSize);
// Show Capture's main window for continued user interaction.
setVisible (true);
// Update ImageArea component with the new image and adjust
// the scrollbars.
ia.setImage (biScreen);
jsp.getHorizontalScrollBar ().setValue (0);
jsp.getVerticalScrollBar ().setValue (0);
// Create a selection Rectangle. It's better to create one Rectangle
// here than a Rectangle each time paintComponent() is called, to reduce
// unnecessary object creation.
rectSelection = new Rectangle ();
// Define the stroke for drawing selection rectangle outline.
bs = new BasicStroke (5, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
0, new float [] { 12, 12 }, 0);
// Define the gradient paint for coloring selection rectangle outline.
gp = new GradientPaint (0.0f, 0.0f, Color.red, 1.0f, 1.0f, Color.white,
true);
// Install a mouse listener that sets things up for a selection drag.
MouseListener ml;
ml = new MouseAdapter ()
{
public void mousePressed (MouseEvent e)
{
// When you start Capture, there is no captured image.
// Therefore, it makes no sense to try and select a sub-image.
// This is the reason for the if (image == null) test.
if (image == null)
return;
destx = srcx = e.getX ();
desty = srcy = e.getY ();
repaint ();
}
};
addMouseListener (ml);
// Install a mouse motion listener to update the selection rectangle
// during drag operations.
MouseMotionListener mml;
mml = new MouseMotionAdapter ()
{
public void mouseDragged (MouseEvent e)
{
// When you start Capture, there is no captured image.
// Therefore, it makes no sense to try and select a
// sub-image. This is the reason for the if (image == null)
// test.
if (image == null)
return;
destx = e.getX ();
desty = e.getY ();
repaint ();
}
};
addMouseMotionListener (mml);
// Draw the selection rectangle if present.
if (srcx != destx || srcy != desty)
{
// Compute upper-left and lower-right coordinates for selection
// rectangle corners.
int x1 = (srcx < destx) ? srcx : destx;
int y1 = (srcy < desty) ? srcy : desty;
int x2 = (srcx > destx) ? srcx : destx;
int y2 = (srcy > desty) ? srcy : desty;
// Establish selection rectangle origin.
rectSelection.x = x1;
rectSelection.y = y1;
// Establish selection rectangle extents.
rectSelection.width = (x2-x1)+1;
rectSelection.height = (y2-y1)+1;
// Draw selection rectangle.
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke (bs);
g2d.setPaint (gp);
g2d.draw (rectSelection);
}
// Crop ImageArea component and adjust the scrollbars if
// cropping succeeds.
if (ia.crop ())
{
jsp.getHorizontalScrollBar ().setValue (0);
jsp.getVerticalScrollBar ().setValue (0);
}
else
showError ("Out of bounds.");
public boolean crop ()
{
// There is nothing to crop if the selection rectangle is only a single
// point.
if (srcx == destx && srcy == desty)
return true;
// Assume success.
boolean succeeded = true;
// Compute upper-left and lower-right coordinates for selection rectangle
// corners.
int x1 = (srcx < destx) ? srcx : destx;
int y1 = (srcy < desty) ? srcy : desty;
int x2 = (srcx > destx) ? srcx : destx;
int y2 = (srcy > desty) ? srcy : desty;
// Compute width and height of selection rectangle.
int width = (x2-x1)+1;
int height = (y2-y1)+1;
// Create a buffer to hold cropped image.
BufferedImage biCrop = new BufferedImage (width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = biCrop.createGraphics ();
// Perform the crop operation.
try
{
BufferedImage bi = (BufferedImage) image;
BufferedImage bi2 = bi.getSubimage (x1, y1, width, height);
g2d.drawImage (bi2, null, 0, 0);
}
catch (RasterFormatException e)
{
succeeded = false;
}
g2d.dispose ();
if (succeeded)
setImage (biCrop); // Implicitly remove selection rectangle.
else
{
// Prepare to remove selection rectangle.
srcx = destx;
srcy = desty;
// Explicitly remove selection rectangle.
repaint ();
}
return succeeded;
}
// Construct a save file-chooser. Initialize the starting directory to
// the current directory, do not allow the user to select the "all files"
// filter, and restrict the files that can be selected to those ending
// with .jpg or .jpeg extensions.
final JFileChooser fcSave = new JFileChooser ();
fcSave.setCurrentDirectory (new File (System.getProperty ("user.dir")));
fcSave.setAcceptAllFileFilterUsed (false);
fcSave.setFileFilter (new ImageFileFilter ());
public boolean accept (File f)
{
// Allow the user to select directories so that the user can navigate the
// file system.
if (f.isDirectory ())
return true;
// Allow the user to select files ending with a .jpg or a .jpeg
// extension.
String s = f.getName ();
int i = s.lastIndexOf ('.');
if (i > 0 && i < s.length ()-1)
{
String ext = s.substring (i+1).toLowerCase ();
if (ext.equals ("jpg") || ext.equals ("jpeg"))
return true;
}
// Nothing else can be selected.
return false;
}
// Present the "save" file-chooser without any file selected.
// If the user cancels this file-chooser, exit this method.
fcSave.setSelectedFile (null);
if (fcSave.showSaveDialog (Capture.this) !=
JFileChooser.APPROVE_OPTION)
return;
// Obtain the selected file. Validate its extension, which
// must be .jpg or .jpeg. If extension not present, append
// .jpg extension.
File file = fcSave.getSelectedFile ();
String path = file.getAbsolutePath ().toLowerCase ();
if (!path.endsWith (".jpg") && !path.endsWith (".jpeg"))
file = new File (path += ".jpg");
// If the file exists, inform the user, who might not want
// to accidentally overwrite an existing file. Exit method
// if the user specifies that it is not okay to overwrite
// the file.
if (file.exists ())
{
int choice = JOptionPane.
showConfirmDialog (null,
"Overwrite file?",
"Capture",
JOptionPane.
YES_NO_OPTION);
if (choice == JOptionPane.NO_OPTION)
return;
}
ImageWriter writer = null;
ImageOutputStream ios = null;
try
{
// Obtain a writer based on the jpeg format.
Iterator iter;
iter = ImageIO.getImageWritersByFormatName ("jpeg");
// Validate existence of writer.
if (!iter.hasNext ())
{
showError ("Unable to save image to jpeg file type.");
return;
}
// Extract writer.
writer = (ImageWriter) iter.next();
// Configure writer output destination.
ios = ImageIO.createImageOutputStream (file);
writer.setOutput (ios);
// Set jpeg compression quality to 95%.
ImageWriteParam iwp = writer.getDefaultWriteParam ();
iwp.setCompressionMode (ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality (0.95f);
// Write the image.
writer.write (null,
new IIOImage ((BufferedImage)
ia.getImage (), null, null),
iwp);
}
catch (IOException e2)
{
showError (e2.getMessage ());
}
finally
{
try
{
// Cleanup.
if (ios != null)
{
ios.flush ();
ios.close ();
}
if (writer != null)
writer.dispose ();
}
catch (IOException e2)
{
}
}
GraphicsEnvironment graphenv = GraphicsEnvironment.getLocalGraphicsEnvironment ();
GraphicsDevice [] screens = graphenv.getScreenDevices ();
BufferedImage [] captures = new BufferedImage [screens.length];
for (int i = 0; i < screens.length; i++)
{
DisplayMode mode = screens [i].getDisplayMode ();
Rectangle bounds = new Rectangle (0, 0, mode.getWidth (), mode.getHeight ());
captures [i] = new Robot (screens [i]).createScreenCapture (bounds);
}
↑返回目录
前一篇: String VS StringBuffer 让你的程序运行得更快
后一篇: java实现的LZW 压缩算法源码