Published 18 Oct, 2022

Java - How to attach custom/existing screenshot in allure report?

Category Java
Modified : Nov 28, 2022
92

Generally, I am using below code to take a screenshot and attach in allure report :

@Attachment(value = "Page Screenshot", type = "image/png")
public static byte[] saveScreenshotPNG(WebDriver driver) {
    return ((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);
}

But now my need is I have already some screenshot on my desktop and want to attach it with an allure report. is that possible?

Answers

There are 1 suggested solutions here and each one has been listed below with a detailed description. The following topics have been covered briefly such as Java, Selenium Webdriver, Allure. These have been categorized in sections for a clear and precise explanation.

28

You can take the existing image and convert it to byte[]. getScreenshotAs() decodes the screenshot string so you might need to do it as well

Java

@Attachment(value = "Page Screenshot", type = "image/png")
public static byte[] saveScreenshotPNG(String path) {
    File file = new File(path);
    BufferedImage bufferedImage = ImageIO.read(file);

    byte[] image = null;
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
        ImageIO.write(bufferedImage, "png", bos);
        image = bos.toByteArray();
    } catch (Exception e) { }

    // if decoding is not necessary just return image
    return image != null ? Base64.getMimeDecoder().decode(image) : null;
}

Python

with open(path, 'rb') as image:
    file = image.read()
    byte_array = bytearray(file)
    allure.attach(byte_array, name="Screenshot", attachment_type=AttachmentType.PNG)