java QQ 캡처 모방 기능 구현


 
 
프로젝트 수요로 인해 QQ 캡처를 모방하는 기능을 썼는데 QQ가 그렇게 잘하지 못했다. 캡처는 주로 서버에 저장된 것이지 그렇지 않았다
프론트 데스크에서 전시하고 전시가 필요할 때 서버에서 찾으면 됩니다.완벽해야 한다.
1. 페이지의 호출
// ,  ( , )
function  screenCapture(){
	    var params="method=screenCapture";
		var url = "<%=basePath%>/NameCheck.do";
	    $.post(url,params,function(megs){
	    		$("#screen").val(megs);
	    });
}

2. 백그라운드 코드 액션
package com.contactlist.action;

import java.awt.GraphicsEnvironment;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;
import com.destination.action.ScreenCapture;
import com.weibo.weibo4j.util.URLEncodeUtils;

public class NameCheckAction extends DispatchAction
{
    /**
     *  
     * 
     * @author Beau Virgill
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @throws Exception
     */

    public ActionForward screenCapture(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception
    {
        System.out.println("-------------------------------- google ----------------------------------in");
        GraphicsEnvironment ge =  GraphicsEnvironment.getLocalGraphicsEnvironment();   
        System.out.println("ge.isHeadless() = " + ge.isHeadless());   
        if (ge.isHeadless()) {   
           System.setProperty("java.awt.headless", "false");   
        }
        String filepath = NameCheckAction.class.getResource("/").getPath();
        String savepath2 = "";
        String osName = System.getProperty("os.name");
        log.info("osName==========" + osName);
        if (osName.charAt(0) == 'W')
        {
            savepath2 = filepath.substring(1, filepath.length() - 16) + "photoUpload/" + "screenCapture.jpg";
        }
        else
        {
            savepath2 = filepath.substring(0, filepath.length() - 16) + "photoUpload" + File.separator
                    + "screenCapture.jpg";
        }
        File tempFile = new File(URLEncodeUtils.decodeURL(savepath2));

        ScreenCapture capture = ScreenCapture.getInstance();
        capture.captureImage();
        System.out.println(URLEncodeUtils.decodeURL(savepath2));
        try
        {
            capture.saveToFile(tempFile);
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        PrintWriter out = response.getWriter();
        out.print(URLEncodeUtils.decodeURL(savepath2));

        return null;
    }

    /**
     * ajax JSON  
     * 
     * @author      Beau Virgill  :( , 。)
     * @param msg
     * @param response
     * @throws Exception
     */

    public void ajaxReturn(HttpServletResponse response, String msg)
    {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = null;
        try
        {
            out = response.getWriter();
            StringBuffer rebuf = new StringBuffer("{msg:\'" + msg + "\'"); //  STRINGBUFFER 
            rebuf.append("}");
            out.println(rebuf.toString());
            System.out.println(rebuf.toString());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            out.flush();
            out.close();
        }
    }

    private int saveFile(FormFile file, String fileSavePath)
    {

        FileOutputStream fileOutput;
        try
        {
            fileOutput = new FileOutputStream(fileSavePath);
            fileOutput.write(file.getFileData());
            fileOutput.flush();
            fileOutput.close();
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
            log.error(" !");
            return 81;
        }
        catch (IOException e)
        {
            e.printStackTrace();
            log.error(" !");
            return 82;
        }
        return 10;
    }

}

3. Action이 호출하는 봉인 캡처 방법
package com.destination.action;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JPanel;

public class ScreenCapture
{
    private static ScreenCapture dafaultCapture=new ScreenCapture();
    private int x1,y1,x2,y2;
    private int recX,recY,recH,recW;
    private boolean isFirstPoint=true;
    private BackgroudImage labFullScreenImage=new BackgroudImage();
    private Robot robot;
    private BufferedImage fullScreenImage;
    private BufferedImage pickedImage;
    private String defaultImageFormater="jpg";
    private JDialog dialog=new JDialog();
    private ScreenCapture(){
      
        try{
            robot=new Robot();
        }catch (AWTException e) {
          System.err.println("Internal Error:"+e);
          e.printStackTrace();
        }
        JPanel cp=(JPanel) dialog.getContentPane();
        cp.setLayout(new BorderLayout());
        labFullScreenImage.addMouseListener(new MouseAdapter(){
            public void mouseReleased(MouseEvent evn){
                isFirstPoint=true;
                pickedImage=fullScreenImage.getSubimage(recX, recY, recW, recH);
                dialog.setVisible(false);
            }
        });
        labFullScreenImage.addMouseMotionListener(new MouseMotionAdapter(){
            public void mouseDragged(MouseEvent evn){
                if(isFirstPoint){
                    x1=evn.getX();
                    y1=evn.getY();
                    isFirstPoint=false;
                }else{
                    x2=evn.getX();
                    y2=evn.getY();
                    int maxX=Math.max(x1, x2);
                    int maxY=Math.max(y1, y2);
                    int minX=Math. min(x1, x2);
                    int minY=Math. min(y1, y2);
                    recX=minX;
                    recY=minY;
                    recW=maxX-minX;
                    recH=maxY-minY;
                  labFullScreenImage.drowRectangle(recX, recY, recW, recH);
                }
            }
            public void mouseMoved(MouseEvent e){
                labFullScreenImage.drowCross(e.getX(), e.getY());
            }
        });
        cp.add(BorderLayout.CENTER,labFullScreenImage);
        dialog.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
        dialog.setAlwaysOnTop(true);
        dialog.setMaximumSize(Toolkit.getDefaultToolkit().getScreenSize());
        dialog.setUndecorated(true);
        dialog.setSize(dialog.getMaximumSize());
        dialog.setModal(true);
    }
    
    public static ScreenCapture getInstance(){
        return dafaultCapture;
    }
    
    public  Icon captureFullScreen(){
        fullScreenImage=robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        ImageIcon icon=new ImageIcon(fullScreenImage);
        return icon;
    }
    
    public void captureImage(){
        dialog.setVisible(false);
        fullScreenImage=robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        ImageIcon icon=new ImageIcon(fullScreenImage);
        labFullScreenImage.setIcon(icon);
        dialog.setVisible(true);
    }
    
    public BufferedImage getPickedImage(){
        return pickedImage;
    }
    
    public ImageIcon getPickedIcon(){
        return new ImageIcon(getPickedImage());
    }
    
    public void saveToFile(File file) throws IOException{
        ImageIO.write(getPickedImage(), defaultImageFormater, file);
    }
    
    public void saveAsPNG(File file) throws IOException{
        ImageIO.write(getPickedImage(), "png", file);
    }
    
    public void saveAsJPEG(File file) throws IOException{
        ImageIO.write(getPickedImage(), "JPEG", file);
    }
    
    public void write(OutputStream out)throws IOException{
        ImageIO.write(getPickedImage(),defaultImageFormater, out);
    }
    

}

4. 봉인된 배경 그림 방법
package com.destination.action;

import java.awt.Graphics;

import javax.swing.JLabel;

public class BackgroudImage extends JLabel{
        int lineX,lineY;
        int x,y,h,w;
        
        public void drowCross(int x,int y){
            lineX=x;
            lineY=y;
            repaint();
        }
        
        public void drowRectangle(int x,int y,int w,int h){
            this.x=x;
            this.y=y;
            this.h=h;
            this.w=w;
            repaint();
        }
        
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            g.drawRect(x, y, w, h);
            String area=Integer.toString(w)+"*"+Integer.toString(h);
            g.drawString(area, x+(int)w/2-15, y+(int)h/2);
            g.drawLine(lineX, 0, lineX, getHeight());
            g.drawLine(0, lineY, getWidth(), lineY);
            
        }

}

좋은 웹페이지 즐겨찾기