如何正确截图Android设备?

时间:2019-05-16 20:39:05

标签: java android

我得到的图像在电话中间有一段,作为右边的伪像。

Android代码

我使用MediaProjectionImageReader

//OnCreate
display = getWindowManager().getDefaultDisplay();
display.getSize(displaySize);
display.getMetrics(displayMetrics);
imageReader = ImageReader.newInstance(displaySize.x, displaySize.y, 
    PixelFormat.RGBA_8888, 2);

//onActivityResult
mediaProjection.createVirtualDisplay("screen", displaySize.x, displaySize.y, 
    displayMetrics.densityDpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, 
    imageReader.getSurface(), null, null);

//ScheduledThread
Image image = imageReader.acquireLatestImage();
if(image != null) {
    final Image.Plane[] planes = image.getPlanes();
    int pixelStride = planes[0].getPixelStride();
    int rowStride = planes[0].getRowStride();
    int rowPadding = rowStride - pixelStride * image.getWidth();

    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
    Bitmap bitmap = Bitmap.createBitmap(image.getWidth() + rowPadding / 
        pixelStride, image.getHeight(), Bitmap.Config.ARGB_8888);
    bitmap.copyPixelsFromBuffer(buffer);

    byte[] byteArray;
    if(bitmap != null) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG,50,byteArrayOutputStream);
        byteArray = byteArrayOutputStream.toByteArray();
        String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
        socket.emit("frame", encoded);
    }
    image.close();
}

Java代码

socket.on("frame", args1 -> {
    byte[] bytes = Base64.getMimeDecoder().decode((String)args1[0]);
    ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
    try {
        BufferedImage img = ImageIO.read(bin);
        int type = img.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : img.getType();
        img = resizeImage(img, type);
        if(!frameOpen){
            openFrame(img.getWidth());
        }
        panel.removeAll();
        panel.add(new JLabel(new ImageIcon(img)));
        frame.pack();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
});


private static BufferedImage resizeImage(BufferedImage originalImage, int type) {
    double ratio = 1.0 * originalImage.getWidth() / originalImage.getHeight();
    int imgHeight = Toolkit.getDefaultToolkit().getScreenSize().height - 100;
    BufferedImage resizedImage = new BufferedImage((int) ((int)imgHeight*ratio), imgHeight, type);
    Graphics2D g = resizedImage.createGraphics();
    g.drawImage(originalImage, 0, 0, (int) ((int)imgHeight*ratio), imgHeight, null);
    g.dispose();
    return resizedImage;
}

结果

如您在图像中所见,在最右边,细线是从图像的中间部分开始的。 Transmitted Screenshot

您认为是什么原因造成的?

编辑:我知道这是android代码中的错误。我的ImageReadercreateVirtualDisplay设置错误吗?

我能够使用以下方法消除黑条:

  

display.getRealSize(displaySize);

但是该线段仍然存在: enter image description here

回购

https://github.com/Decapitated/Android-Viewer

0 个答案:

没有答案