@@ -8,6 +8,9 @@ module Screenshot
88 FULL_WARNING = "Ignoring :selector or :area in #screenshot since full: true was given at %s"
99 AREA_WARNING = "Ignoring :area in #screenshot since selector: was given at %s"
1010
11+ DEFAULT_SCREENSHOT_FORMAT = "png"
12+ SUPPORTED_SCREENSHOT_FORMAT = %w[ png jpeg jpg webp ] . freeze
13+
1114 DEFAULT_PDF_OPTIONS = {
1215 landscape : false ,
1316 paper_width : 8.5 ,
@@ -41,7 +44,7 @@ module Screenshot
4144 # @option opts [:base64, :binary] :encoding
4245 # The encoding the image should be returned in.
4346 #
44- # @option opts ["jpeg", "png"] :format
47+ # @option opts ["jpeg", "jpg", " png", "webp "] :format
4548 # The format the image should be returned in.
4649 #
4750 # @option opts [Integer] :quality
@@ -71,8 +74,11 @@ module Screenshot
7174 # @example Save on the disk in JPG:
7275 # page.screenshot(path: "google.jpg") # => 30902
7376 #
77+ # @example Save to Base64 in WebP with reduce quality:
78+ # page.screenshot(format: 'webp', quality: 60) # "iVBORw0KGgoAAAANS...
79+ #
7480 # @example Save to Base64 the whole page not only viewport and reduce quality:
75- # page.screenshot(full: true, quality: 60) # "iVBORw0KGgoAAAANS...
81+ # page.screenshot(full: true, format: 'jpeg', quality: 60) # "iVBORw0KGgoAAAANS...
7682 #
7783 # @example Save with specific background color:
7884 # page.screenshot(background_color: Ferrum::RGBA.new(0, 0, 0, 0.0))
@@ -210,14 +216,24 @@ def screenshot_options(path = nil, format: nil, scale: 1.0, **options)
210216 screenshot_options
211217 end
212218
213- def format_options ( format , path , quality )
214- format ||= path ? File . extname ( path ) . delete ( "." ) : "png"
215- format = "jpeg" if format == "jpg"
216- raise "Not supported options `:format` #{ format } . jpeg | png" if format !~ /jpeg|png/i
219+ def format_options ( screenshot_format , path , quality )
220+ if !screenshot_format && path # try to infer from path
221+ extension = File . extname ( path ) . delete ( "." ) &.downcase
222+ screenshot_format = extension if extension && !extension . empty?
223+ end
224+
225+ screenshot_format ||= DEFAULT_SCREENSHOT_FORMAT
226+ screenshot_format = screenshot_format . to_s
227+ unless SUPPORTED_SCREENSHOT_FORMAT . include? ( screenshot_format )
228+ raise "Not supported options `:format` #{ screenshot_format } . #{ SUPPORTED_SCREENSHOT_FORMAT . join ( ' | ' ) } "
229+ end
230+
231+ screenshot_format = "jpeg" if screenshot_format == "jpg"
217232
218- quality ||= 75 if format == "jpeg"
233+ # Chrome supports screenshot qualities for JPEG and WebP
234+ quality ||= 75 if screenshot_format != "png"
219235
220- [ format , quality ]
236+ [ screenshot_format , quality ]
221237 end
222238
223239 def area_options ( full , selector , scale , area = nil )
0 commit comments