JAVA实现Android的PC端截图并显示图片

illusionskyboy 2013-06-27 03:55:36
本来我是要做一个点击图片获取图片上的坐标的,但是现在时间有限,能力有限,太难了,我本是一个软件测试员,代码都是自学的,还是现学现做的,代码了解深度不够,就只能写到这里了。在这提供一些需要的人,并且也希望有人能帮我完善和优化,能实现鼠标点击图片时获取点击点的图片上的像素(比如200*300的像素)。不说了,上代码,大家多指教了!
这是JImagePane类,主要实现图片的缩放显示,显示质量不是很好

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
* 可设置背景图片的JPanel,提供了4种显示背景图片的方式:居中、平铺、拉伸、缩放居中。
* 未设置背景图片的情况下,同JPanel。
* 本来是要实现点击图片获取图片坐标(像素),时间限制,就到这了,希望大家能帮我实现并联系我,谢谢大家!
* 我的邮箱:xingghhao@qq.com
* @author 003
*/
public class JImagePane extends JPanel
{
private static final long serialVersionUID = -8251916094895167058L;

/**
* 居中
*/
public static final String CENTRE = "Centre";

/**
* 平铺
*/
public static final String TILED = "Tiled";

/**
* 拉伸
*/
public static final String SCALED = "Scaled";

/**
* 按比例缩放
*/
public static final String ZOOM = "zoom";

/**
* 背景图片
*/
private Image backgroundImage;

/**
* 背景图片显示模式
*/
private String imageDisplayMode;

/**
* 背景图片显示模式索引(引入此属性有助于必要时扩展)
*/
private int modeIndex;

/**
* 构造一个没有背景图片的JImagePane
*/
public JImagePane()
{
this(null, CENTRE);
}

/**
* 构造一个具有指定背景图片和指定显示模式的JImagePane
* @param image 背景图片
* @param modeName 背景图片显示模式
*/
public JImagePane(Image image, String modeName)
{
super();
setBackgroundImage(image);
setImageDisplayMode(modeName);
}

/**
* 设置背景图片
* @param image 背景图片
*/
public void setBackgroundImage(Image image)
{
this.backgroundImage = image;
this.repaint();
}

/**
* 获取背景图片
* @return 背景图片
*/
public Image getBackgroundImage()
{
return backgroundImage;
}

/**
* 设置背景图片显示模式
* @param modeName 模式名称,取值仅限于ImagePane.TILED ImagePane.SCALED ImagePane.CENTRE
*/
public void setImageDisplayMode(String modeName)
{
if(modeName != null)
{
modeName = modeName.trim();

//居中
if(modeName.equalsIgnoreCase(CENTRE))
{
this.imageDisplayMode = CENTRE;
modeIndex = 0;
}
//平铺
else if(modeName.equalsIgnoreCase(TILED))
{
this.imageDisplayMode = TILED;
modeIndex = 1;
}
//拉伸
else if(modeName.equalsIgnoreCase(SCALED))
{
this.imageDisplayMode = SCALED;
modeIndex = 2;
}
//按比例缩放并居中显示
else if(modeName.equalsIgnoreCase(ZOOM))
{
this.imageDisplayMode = ZOOM;
modeIndex = 3;
}

this.repaint();
}
}

/**
* 获取背景图片显示模式
* @return 显示模式
*/
public String getImageDisplayMode()
{
return imageDisplayMode;
}

/**
* 绘制组件
* @see javax.swing.JComponent#paintComponent(Graphics)
*/
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);

//如果设置了背景图片则显示
if(backgroundImage != null)
{
int width = this.getWidth();
int height = this.getHeight();
int imageWidth = backgroundImage.getWidth(this);
int imageHeight = backgroundImage.getHeight(this);

switch(modeIndex)
{
//居中
case 0:
{
int x = (width - imageWidth) / 2;
int y = (height - imageHeight) / 2;
g.drawImage(backgroundImage, x, y, this);
break;
}
//平铺
case 1:
{
for(int ix = 0; ix < width; ix += imageWidth)
{
for(int iy = 0; iy < height; iy += imageHeight)
{
g.drawImage(backgroundImage, ix, iy, this);
}
}

break;
}
//拉伸
case 2:
{
g.drawImage(backgroundImage, 0, 0, width, height, this);
break;
}

//按比例缩放并居中显示
case 3:
{
int imagesMAX = imageWidth > imageHeight ? imageWidth : imageHeight;
int imagesMIN = imageWidth < imageHeight ? imageWidth : imageHeight;
int newWidth = height*imagesMIN/imagesMAX;
int newHeight = width*imagesMAX/imagesMIN;

if(width >= height)
{
if(newWidth > width)
{
g.drawImage(backgroundImage, 0, (height-newHeight)/2, newHeight, height, this);
}
else
{
g.drawImage(backgroundImage, (width-newWidth)/2, 0, newWidth, height, this);
}
}
else
{
if(newHeight > height)
{
g.drawImage(backgroundImage, (width-newWidth)/2, 0, newWidth, height, this);
}
else
{
g.drawImage(backgroundImage, 0, (height-newHeight)/2, width, newHeight, this);
}
}
//System.out.println(windowsMIN);
//System.out.println(Math.round((imagesMIN*1f)/(imagesXY*1f)));
break;
}
}
}
}

public static void main(String[] args)
{
ScreenShot ss = new ScreenShot();
String[] dore = {"-d","test.png"};
//JOptionPane.showMessageDialog( null,"点击确定后截图!截图比较慢!");
//ss.draw(dore);
JFrame frame = new JFrame("JImagePane Test");
Image iamge = new ImageIcon("test.png").getImage();
JImagePane imagePane = new JImagePane(iamge, JImagePane.CENTRE);
frame.getContentPane().add(imagePane, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
...全文
375 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
illusionskyboy 2013-06-27
  • 打赏
  • 举报
回复
这是实现对Android手机进行截图的(终端必须是真机,如果是模拟器,可以修改“args=new String[]{"-d","test.png"};”变成“args=new String[]{"-e","test.png"};”)

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.Log;
import com.android.ddmlib.RawImage;
import com.android.ddmlib.TimeoutException;
import com.android.ddmlib.Log.ILogOutput;
import com.android.ddmlib.Log.LogLevel;


public class ScreenShot {

	 public static void draw(String[] args) {
		 args=new String[]{"-d","test.png"};
	        boolean device = false;
	        boolean emulator = false;
	        String serial = null;
	        String filepath = null;
	        boolean landscape = false;

	        if (args.length == 0) {
	            printUsageAndQuit();
	        }

	        // parse command line parameters.
	        int index = 0;
	        do {
	            String argument = args[index++];

	            if ("-d".equals(argument)) {
	                if (emulator || serial != null) {
	                    printAndExit("-d conflicts with -e and -s", false /* terminate */);
	                }
	                device = true;
	            } else if ("-e".equals(argument)) {
	                if (device || serial != null) {
	                    printAndExit("-e conflicts with -d and -s", false /* terminate */);
	                }
	                emulator = true;
	            } else if ("-s".equals(argument)) {
	                // quick check on the next argument.
	                if (index == args.length) {
	                    printAndExit("Missing serial number after -s", false /* terminate */);
	                }

	                if (device || emulator) {
	                    printAndExit("-s conflicts with -d and -e", false /* terminate */);
	                }

	                serial = args[index++];
	            } else if ("-l".equals(argument)) {
	                landscape = true;
	            } else {
	                // get the filepath and break.
	                filepath = argument;

	                // should not be any other device.
	                if (index < args.length) {
	                    printAndExit("Too many arguments!", false /* terminate */);
	                }
	            }
	        } while (index < args.length);

	        if (filepath == null) {
	            printUsageAndQuit();
	        }

	        Log.setLogOutput(new ILogOutput() {
	            public void printAndPromptLog(LogLevel logLevel, String tag, String message) {
	                System.err.println(logLevel.getStringValue() + ":" + tag + ":" + message);
	            }

	            public void printLog(LogLevel logLevel, String tag, String message) {
	                System.err.println(logLevel.getStringValue() + ":" + tag + ":" + message);
	            }
	        });

	        // init the lib
	        // [try to] ensure ADB is running
	        String adbLocation = System.getProperty("com.android.screenshot.bindir"); //$NON-NLS-1$
	        if (adbLocation != null && adbLocation.length() != 0) {
	            adbLocation += File.separator + "adb"; //$NON-NLS-1$
	        } else {
	            adbLocation = "adb"; //$NON-NLS-1$
	        }

	        AndroidDebugBridge.init(false /* debugger support */);

	        try {
	            AndroidDebugBridge bridge = AndroidDebugBridge.createBridge(
	                    adbLocation, true /* forceNewBridge */);

	            // we can't just ask for the device list right away, as the internal thread getting
	            // them from ADB may not be done getting the first list.
	            // Since we don't really want getDevices() to be blocking, we wait here manually.
	            int count = 0;
	            while (bridge.hasInitialDeviceList() == false) {
	                try {
	                    Thread.sleep(100);
	                    count++;
	                } catch (InterruptedException e) {
	                    // pass
	                }

	                // let's not wait > 10 sec.
	                if (count > 100) {
	                    System.err.println("Timeout getting device list!");
	                    return;
	                }
	            }

	            // now get the devices
	            IDevice[] devices = bridge.getDevices();

	            if (devices.length == 0) {
	                printAndExit("No devices found!", true /* terminate */);
	            }

	            IDevice target = null;

	            if (emulator || device) {
	                for (IDevice d : devices) {
	                    // this test works because emulator and device can't both be true at the same
	                    // time.
	                    if (d.isEmulator() == emulator) {
	                        // if we already found a valid target, we print an error and return.
	                        if (target != null) {
	                            if (emulator) {
	                                printAndExit("Error: more than one emulator launched!",
	                                        true /* terminate */);
	                            } else {
	                                printAndExit("Error: more than one device connected!",true /* terminate */);
	                            }
	                        }
	                        target = d;
	                    }
	                }
	            } else if (serial != null) {
	                for (IDevice d : devices) {
	                    if (serial.equals(d.getSerialNumber())) {
	                        target = d;
	                        break;
	                    }
	                }
	            } else {
	                if (devices.length > 1) {
	                    printAndExit("Error: more than one emulator or device available!",
	                            true /* terminate */);
	                }
	                target = devices[0];
	            }

	            if (target != null) {
	                try {
	                    System.out.println("Taking screenshot from: " + target.getSerialNumber());
	                    getDeviceImage(target, filepath, landscape);
	                    System.out.println("Success.");
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            } else {
	                printAndExit("Could not find matching device/emulator.", true /* terminate */);
	            }
	        } finally {
	            AndroidDebugBridge.terminate();
	        }
	    }

	    /**
	     * Grab an image from an ADB-connected device.
	     */
	    private static void getDeviceImage(IDevice device, String filepath, boolean landscape)
	            throws IOException {
	        RawImage rawImage;

	        try {
	            rawImage = device.getScreenshot();
	        } catch (TimeoutException e) {
	            printAndExit("Unable to get frame buffer: timeout", true /* terminate */);
	            return;
	        } catch (Exception ioe) {
	            printAndExit("Unable to get frame buffer: " + ioe.getMessage(), true /* terminate */);
	            return;
	        }

	        // device/adb not available?
	        if (rawImage == null)
	            return;

	        if (landscape) {
	            rawImage = rawImage.getRotated();
	        }

	        // convert raw data to an Image
	        BufferedImage image = new BufferedImage(rawImage.width, rawImage.height,
	                BufferedImage.TYPE_INT_ARGB);

	        int index = 0;
	        int IndexInc = rawImage.bpp >> 3;
	        for (int y = 0 ; y < rawImage.height ; y++) {
	            for (int x = 0 ; x < rawImage.width ; x++) {
	                int value = rawImage.getARGB(index);
	                index += IndexInc;
	                image.setRGB(x, y, value);
	            }
	        }

	        if (!ImageIO.write(image, "png", new File(filepath))) {
	            throw new IOException("Failed to find png writer");
	        }
	    }

	    private static void printUsageAndQuit() {
	        // 80 cols marker:  01234567890123456789012345678901234567890123456789012345678901234567890123456789
	        System.out.println("Usage: screenshot2 [-d | -e | -s SERIAL] [-l] OUT_FILE");
	        System.out.println("");
	        System.out.println("    -d      Uses the first device found.");
	        System.out.println("    -e      Uses the first emulator found.");
	        System.out.println("    -s      Targets the device by serial number.");
	        System.out.println("");
	        System.out.println("    -l      Rotate images for landscape mode.");
	        System.out.println("");

	        System.exit(1);
	    }

	    private static void printAndExit(String message, boolean terminate) {
	        System.out.println(message);
	        if (terminate) {
	            AndroidDebugBridge.terminate();
	        }
	        System.exit(1);
	    }
}
工程源码:http://download.csdn.net/detail/illusionskyboy/5659291

51,410

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧