Yehuda Miller
Yehuda Miller

Reputation: 329

How can I reduce the quality or dimensions of a screenshot taken with selenium?

I am running a suite of tests in parallel using Cucumber and then grouping them all together into a single HTML report. On failed tests a screenshot is taken of my browser and embedded as a png in the report. For test runs which have a lot of failures the report can grow to as large as 50MB and it takes forever for the report to load.

Is there a way to take a screenshot, reduce the size of it, and only then embed it into the report so that I can get the file size down? Assume that the images need to be embedded and cannot be stored as files separate to the report.

Upvotes: 3

Views: 3577

Answers (1)

Florent B.
Florent B.

Reputation: 42528

Selenium doesn't provide a way to resize a screenshot. Though, you can easily override the "screenshot_as" method to make it return a smaller image. This example use the "chunky_png" library to resize each screenshot to 80% of the original size:

require 'selenium-webdriver'
require 'chunky_png'

module Selenium
  module WebDriver
    module DriverExtensions
      module TakesScreenshot

        def screenshot_as(format)

          # take a screenshot and load it with ChunkyPNG
          img = ChunkyPNG::Image.from_blob(bridge.getScreenshot.unpack("m")[0])

          # reduce the size to 80% of the original size
          img = img.resize((img.width * 0.8).floor, (img.height * 0.8).floor)

          case format
            when :base64
              img.to_blob.pack('A*m')
            when :png
              img.to_blob
            else
              raise Error::UnsupportedOperationError, "unsupported format: #{format.inspect}"
          end
        end

      end
    end
  end
end

Upvotes: 1

Related Questions