Get image from M3dView::readColorBuffer in Viewport 2

Although the API is marked as obsolete, it is the easiest way to get a screenshot from Viewport in Maya and many plug-ins are still using it.

But if you are trying to get a MImage from Viewport 2, you may have some problem with your previous Python code like this.

import maya.OpenMaya as openmaya
import maya.OpenMayaUI as openmayaUI
view = openmayaUI.M3dView.active3dView()
img = openmaya.MImage()
view.readColorBuffer(img)

This code will not work because in Viewport 2, the image is stored as float and the default format of MImage is BGRA byte.

The solution is simple, make MImage a float image. Replace the last line above with following code snippet.

if view.getRendererName() == view.kViewport2Renderer:
img .create(view.portWidth(), view.portHeight(), 4, openmaya.MImage.kFloat)
view.readColorBuffer(img)
img.convertPixelFormat(openmaya.MImage.kByte)
else:
view.readColorBuffer(img)

You will get a BGRA byte image in the end like the old time:)


Comments

Leave a Reply

Discover more from Autodesk Developer Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading