Este artigo resume os métodos de captura de tela comuns de implementação de programação Java. Compartilhe -o para sua referência, como segue:
Método 1:
importar java.awt.desktop; importar java.awt.dimension; importar java.awt.rectangle; importar java.awt.robot; importar java.awt.toolkit; importar java.aww t.image.bufredimage; importar java.io.io. Arquivo; importar javax.imageio.imageio; classe pública capturescreen {public static void capturescreen (nome do arquivo de string, pasta string) lança exceção {dimens screenSize = Toolkit.getDefaultToolkit (). GetScReensize (); Robô robot = novo robô (); = novo arquivo (ScreenFile, pasta); Desktop.getDesktop () .open (f); / TODO Gerado Bloco de Catch E.PrintStackTrace ();Método 2:
pacote com.qiu.util; importar java.io.*; importar javax.swing.*; importar java.awt.*; importar java.awt.event.*; importar java.awt.image. imageio. ); ); captura. } Screencapture privado () {tente {robot = new Robot (); diálogo. Rech); (); int minx = matemática .Min (x2, x2); , Recy, Recw, Rech); Dialog.SetCursor (Cursor .getmaximumsize ()); novo retângulo (Toolkit.getDefaultToolkit () .getScreensize ()); = Robot.CreatesCerenche (novo retângulo (Toolkit.GetDefaultToolkit () .getScreensize ()); Após a captura* / public bufferImage getpickedImage () {return pickedImage; Formato * * @Deprecat Ed substituído por SAVEASPNG (arquivo de arquivo) ** / @Deprecated public void Savetofile (arquivo de arquivo) lança ioexception {imageio.write (getPickedImage (), defaultImeformater, arquivo); No formato png*/ public void Savespng (arquivo de arquivo) lança ioexception {imageio.write (getPickedImage (), "png", arquivo); lança ioe xception {imageio.write (getPickedImage (), "jpeg", arquivo); ); ndimage labfullScreenImage = new BackgroundImage (); estende Jlabel {public void PaintConent (gráficos g) {super.paintcomponent (g); ); liney, getwidth (), liney); ;Método 3:
Como é minimizado para o palete do sistema, um ícone de paletes ainda é necessário.
A parte principal do código da captura de tela é:
Robot ro = new robot (); Toolkit tk = Toolkit.getDefaultToolkit (); dimensão di = tk.getScreensize (); retângulo rec = novo retângulo (0,0, di.widt h, di.height); bufedimage bi = ro CreateScreencapture (rec);
(O código -fonte é do CSDN)
importar java.awt.*; importar java.awt.datatransfer.dataflavor; importar java.awt.datatransfer.transferable; importar java.awt.datatransfer.unsupportflavore xception; import java.awt.event.*; importação Importar java.io.*; Importar Javax.Imageio Jtabbedpane jtp; // um único local muitas fotos private int Índice; // Um índice que sempre aumentará, usado para identificar imagens privadas jradiobutton java, sistema; // interface java, interface do sistema/** cria uma nova instância do capturascreen* / ::::::::::::::::::::::::Here :::::::::::::::::::heone:::::::::::::::::::ute : ::::::::::::::::::::::Here :::::::::::::::::::hee :::::::::::::::::heo the ::::::::::::::::::::::::::::here ::: public CaptureScreen () {Super ("Scream Screen Capture Software (terceira edição)"); SetLonga e Uimanager.getSystemLear TOP, JTabbedPane.scroll_tab_layout); isto); Jlabel ("Captura de tela", Jlabel.Center); ); JPanel (); // O painel com dois botões de rádio jp.add (java = novo jradiobutton ("interface java"); this); novo jpanel (); : ::::::::::::::::::::::Here :::::::::::::::::::hee :::::::::::::::::heo the : ::::::::::::::::::::::Here :::::::::::::::::::hee :::::::::::::::::heo the : ::::::::::::::::::::::Here :::::::::::::::::::hee :::::::::::::::::heo the : ::::::::::::::::::::::Here :::::::::::::::::::hee :::::::::::::::::heo the : ::::::::::::::::::::::::here ::::::::::::::::::heone :::::: .getContentPane (). Add (All, BorderLayout .Sout); {public void WindowClosing (WindowEvent) {CaptureScreen.This.SetVisible (false); () .getResource ("bg.gif")); ActionEvent ae) {JoptionPane.ShowMessAgedialog (capturascreen.This, "<html> <font color = Red> <Center> <H 2> SOBRE </H2> </CENTER> </font>" + "Este é um java puro Programa de captura de tela <br> Adicionar à base anterior, algumas funções comumente usadas, <br> " +", por exemplo, salvamento em lote, vários clipes e copiar para a placa de pasta do sistema. Qualquer dúvida durante o uso, não hesite em entrar em contato conosco. </font> </html> ");}}); pm.addseparator (); pm.add (new Menuitem (" Mostrar janela principal ")). AddactionListener (new ActionListener () {public void ActionPormed (ActionEvent AE) {Capturascreen.This.SetVisible (true); ); "Captura de tela Java", PM); Excepção exe) {exe.printStackTrace (); Adicionado, // a coisa atual precisa ser limpa e o tabpão é colocado novamente se (index == 0) {c.removeall (); Basta adicionar um painel ao Tabpane diretamente // e você não precisa fazer nada} picpanel pic = novo picpanel (get); pic); Ro = novo robô (); (Rec); (verdadeiro); Todas as imagens */ public void Dosaveall () {if (jtp.gettabcount () == 0) {joptionpane.showMessagedialog (this, "a imagem não pode estar vazia !!", "erro", joptionpane.error_message); } Jfilechooser jfc = novo jfilechooser (""); (New JPGFilter () )); Ext = file.toStrin G (). TolowerCase (); Sobre = "PNG"; {ext = ext.substring (0, ext.lastIndexOf (ab out.tolowercase ()); }} // A classe do thread usada especialmente para salvar todas as imagens, ele também precisa exibi -la salvada barra de progresso private classe saveallthread estende o jdialog implementa runnable {private string name; // nomes de arquivo private string ext; // formato de arquivo privado jProgressBar j pb; // uma barra de progresso private jlabel info; // Uma barra de exibição de informações Private int alltask, dotask; // todas as tarefas, tarefas concluídas públicas SavealLthread (nome da string, string ext) {super (capturascreen.This, "salvar" , verdadeiro); .Setminimum (0); this.add (info, borderlayout.nor th); ) .start (); {Picpanel pp = (picpanel) jtp.getcomponente (i); setText ("<html> <b> Salvando para: </b> <br>"+f.toString ()+"</html>"); SetValue (dotações); this.dispose (); isto, "a imagem não pode ser vazia !! novo BMPFilter (); .getSelectedFile (); Jpg "; if (! Ext.endSwith (". Jpg ")) {string ns = ext+". if (! Ext.endswith (". Ext.endSwith ("BMP") {String ns = ext+". BMP"; (".gif")) {string ns = ext+". gif"; ! ");} else JoptionPane.ShowMessAgedialog (isto," Salvar falhou! ");}} Catch (Excepção exe) {exe.printStacktrace ();}} /** *Processamento público adiciona a imagem atual ao método da área de transferência * / public void Docopy (Final BufferImage Image) {Try {if (get == null) {JoptionPane.ShowMessagedialog (this, "a imagem não pode estar vazia !!", "Erro", JoptionPane. Error_message); novo transferível () {public DataFavor [] getTransferdataflaVors () {Retorne o novo DataFavor [] {DataFavor.ImageFavor}; Flavor) lança UNSUPORTEDFLAVERECIMENTO, IoException {if (ISDataFlaVorSupportd (sabor) Retorne Imagem; , "Copie a placa de pasta do sistema !!"); Error_message); getSource (); Uimanager .getcrossplatformlowsandfeelclassName ()); ); e pode -se colocar no painel de tabpano // também existe seu próprio conjunto de métodos para lidar com salvar e copiar a classe privada picpanel estende o jpanel implementa o ActionListener {jbutton salvar, copiar, fechar; // bufferiMag, que indica salvamento, copiar, fechar, fechar, BULTO BUBLEIRAGEM E GET; ) {save = novo jbutton ("Salvar (s)"); '); JLAB EL ICON = novo JLABEL (NOVO IMAGEM (GET); (este); ) {docy (get); () {} public boolean Acep (arquivo de arquivo) {if (file.toString (). ToLowerCase (). ENDSWITH (" String getDe script () {return " *.bmp (bmp image)"; arquivo) {if (file.toString () .tolowercase (). J pg (jpg imagem) ";}} // Salvar filtros no formato gif private Classe giffilter estende javax.swing.fileChooser.filefilter {public giffilter () {} public boolean aceit (arquivo de arquivo) {if (fi le.toString (} ) .tolowercase (). // Salvar o formato PNG Filter Classe Private Classe pngfilter estende Javax.swing.fileChooser.FileFilter {public boolean aceit (arquivo de arquivo) {if (file.toString (). ToLowerCase (). EndSwith (". ()) {return true; Ments MouseListener, MousemotionListener {Private BufferImage BI; /Indique a área selecionada Cursor privado CS = New Cursor (cursor.crosshair_cursor); // indica o estado do mouse em estados gerais privados atual = estados.default; // indicam o atual retângulo privado de edição de edição [] rec; // indica o Área dos oito pontos de edição/ :::::::::::::::::::::::::here :::::::::::::::::::ree:::::::::::::::::::ree they ::::::::::::::ree of::::::::::::::::::::::::::::::::::::::::: : ::::::::::::::::::::::Here :::::::::::::::::::hee :::::::::::::::::heo the : :::::::::::::::::::::::::Here ::::::::::::::::::::utee ::: ::::::::::::::::::. public static int start_x = 1; Somente esses dois precisam ser alterados no ponto privado P = new Point (); // A localização atual do mouse move o show booleano privado = true; // Se você deve exibir um prompt .S Não exibe mais a temperatura pública (JFROM JF, BUPS, INT LIDURA, INT) {this.jf = jf; this.addmousemotionListener (this); ); g.drawline (startx, endy, endx, endy); ENDX; : ::::::::::::::::::::::Here :::::::::::::::::::hee :::::::::::::::::heo the : ::::::::::::::::::::::Here :::::::::::::::::::hee :::::::::::::::::heo the ::::::::::::::::::; 2,5,5); -2,5,5); Starty-2,5,5); ] = novo retângulo (x1-5, y-5,10,10); ] = novo retângulo ((startx> endx? startx: endx) -5, y1-5,10,10); ? starty: endy) -5,10,10); X-5, (Starty> Endy? Starty: Endy) -5,10, 10); (Cor.cyan); G.DrawString ("Por favor, mantenha pressionado o botão esquerdo do mouse e não coloque a área da captura de tela", PX, P.Y+15); , oeste, etc. Void privado (Estados Break; 0; = (starty> endy? end_y: start_y); Start_x); mouseMoved (Mouseevent Me) {DomouseMoved (Me); A região que você deseja selecionar cada vez que o Void privado domouseMoved (Mouseevent Me) {if (select.contains (me.getPoint ())) {this.setCursor (New Cursor (cursor.move_cursor)); else {estados [] st = estados.Values (); [i]; Mouseevent me) {} public void mousedrag ged (mouseevent me) {int x = me.getx (); Starty+= (Y-TEMPY); ) {if (currentx == start_x) {startx+= (x-tempx); | atual == estados.north_east || atualização == estados.north_east || y; tempx = x; = false; true; Mouseevent me) {if (me.getClickCount () == 2) {// retângulo Rec = novo retângulo (estrela tx, starty, math.abs (endx -startx), math.abs (endy -start)); = me.getPoint (); .getsubimage (selecione.x, selecione, selecione.Height); x+ select.width> = this.getwidth ()) {wid = this.getwidth ()-select.x; ) -Select.y; []) {Swingutities.invokelater (new Runnable () {public void run () {new CaptureScreen ();}}); // indicates the northwest corner of NORTH(new Cursor(Cursor.N_RESIZE_CURSOR)), NORTH_EAST(new Cursor(Cursor.NE _RESIZE_CURSOR)), EAST(new Cursor(Cursor .E_RESIZE_CURSOR)), SOUTH_EAST(new Cursor(Cursor.SE_RESIZE_CURSOR) ), South (New Cursor (cursor.s_resize_cursor)), South_west (New Cursor (Cursor.sw_ ressequed_cursor)), West (New Cursor (Cursor.W_Resize_Cursor)), Move (New Cursor (Cursor.Move_Cursor)), Deformats), Move (New Cursor ( Cursor (cursor.default_cursor);Espero que este artigo seja útil para a programação Java de todos.