mirror of
https://github.com/blender/blender
synced 2026-09-29 04:37:17 +03:00
PyAPI: add bpy.types.Window.screenshot() method
Capture the contents of a window as a read-only `memoryview` of RGBA bytes shaped `(height, width, 4)`, matching numpy's image convention. Advantages over the operator for the Python API: - It's not possible to set the image format from Python. - It wasn't possible to capture pixel data without writing it to disk. The documentation example shows how a screenshot can be captured and written to an image file using imbuf. Ref !158030
This commit is contained in:
parent
f0c23f2ab7
commit
05b30f7c35
5 changed files with 267 additions and 0 deletions
40
doc/python_api/examples/bpy.types.Window.screenshot.0.py
Normal file
40
doc/python_api/examples/bpy.types.Window.screenshot.0.py
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
"""
|
||||
Save 3D Viewport to a PNG
|
||||
+++++++++++++++++++++++++
|
||||
|
||||
Capture the 3D viewport's main region from the current window
|
||||
and write it to a PNG file using :mod:`imbuf`.
|
||||
"""
|
||||
|
||||
import bpy
|
||||
import imbuf
|
||||
|
||||
window = bpy.context.window
|
||||
|
||||
# Locate the 3D viewport (if any).
|
||||
region = None
|
||||
for area in window.screen.areas:
|
||||
if area.type == 'VIEW_3D':
|
||||
for region_iter in area.regions:
|
||||
if region_iter.type == 'WINDOW':
|
||||
region = region_iter
|
||||
break
|
||||
break
|
||||
|
||||
if region is not None:
|
||||
# The end coordinate is not inclusive, like Python slicing.
|
||||
region_rect = (
|
||||
(region.x, region.y),
|
||||
(region.x + region.width, region.y + region.height),
|
||||
)
|
||||
pixels = window.screenshot(region=region_rect)
|
||||
height, width = pixels.shape[0], pixels.shape[1]
|
||||
|
||||
ibuf = imbuf.new((width, height))
|
||||
ibuf.file_type = 'PNG'
|
||||
with ibuf.with_buffer('BYTE', write=True) as buf:
|
||||
# The cast produces a zero-copy 1-D view of the same bytes.
|
||||
# Currently only 1-D copies are supported by Python.
|
||||
buf.cast('B')[:] = pixels.cast('B')
|
||||
|
||||
imbuf.write(ibuf, filepath="/tmp/viewport.png")
|
||||
Loading…
Add table
Add a link
Reference in a new issue