2

I would like to take a screenshot of my QGIS area, which I am working on.

It does look pretty much as you can see below:

enter image description here

I would like to grab only the visible area of my map. I am not talking about map canvas, as mentioned here:

Save map canvas as image with Python in QGIS

PyQGIS make screenshot of mapCanvas after setExtent is called

or here

Saving Map Canvas as PNG with transparent background programmatically with QGIS?

or here

Export Map Canvas QGIS

I simply want to have an option to grab the screen from my QGIS working area defined by it visible bounds (after dock windows visible).

I tried some of the codes, but they didn't work:

 mainPath = 'C:\\Users\\mk\\Desktop\\AX\\Pre survey\\Tyton\\'
 filename = 'StrandAAA'
 imageType = "png"

 imageWidth_mm = 400
 imageHeight_mm = 160
 dpi = 300

 mapRenderer = iface.mapCanvas().mapRenderer()

 c = QgsComposition(mapRenderer)
 c.setPlotStyle(QgsComposition.Print)

 c.setPaperSize(400, 160)

 x, y = 0, 0
 w, h = c.paperWidth(), c.paperHeight()
 composerMap = QgsComposerMap(c, x ,y, w, h)
 c.addItem(composerMap)

 # get all items and disable the backgrounds
 itemList = c.items()
 c.removeItem(itemList[2])
 c.removeItem(itemList[2])
 itemList[2].setBackgroundEnabled(False)
 itemList[3].setBackgroundEnabled(False)
 # add them to the composition
 c.addItem(itemList[2])
 c.addItem(itemList[3])

 c.refreshItems()
 c.refreshDataDefinedProperty(QgsComposerObject.AllProperties)

 c.setPrintResolution(dpi)
 dpmm = dpi / 25.4
 width = int(dpmm * c.paperWidth())
 height = int(dpmm * c.paperHeight())

 # create output image and initialize it
 # image = QImage(QSize(width, height), QImage.Format_ARGB32)
 image = QImage(QSize(width, height), QImage.Format_ARGB32_Premultiplied)
 image.setDotsPerMeterX(dpmm * 1000)
 image.setDotsPerMeterY(dpmm * 1000)
 #image.fill(0)

 imagePainter = QPainter(image)

 # This part does not seem to have any effect
 #brush = QBrush(Qt.BrushStyle(0)) # transparent brush
 #
 #imagePainter.setBackgroundMode(0)
 #c.setBackgroundBrush(brush)

 c.renderPage( imagePainter, 0 )
 imagePainter.end()


 imageFilename =  mainPath + filename + '.' + imageType
 image.save(imageFilename, imageType)
 print 'image saved'
 print 'done

but it didn't work, the same as:

  vlayer.select(ID)
 qgis.utils.iface.actionZoomToSelected().trigger()
 vlayer.deselect(ID)
 qgis.utils.iface.mapCanvas().saveAsImage('C:\\Users\\mk\\Desktop\\AX\\Pre survey\\Tyton\\feature.png')

The solution is shown on the YT channel here also wasn't successful

https://www.youtube.com/watch?v=17AXqO5_s7g&ab_channel=OpenSourceOptions

I think I am closer to this solution:

Is it possible to take automatically a "screenshot" of my selected feature in QGIS using Python?

butt instead of selected feature I need the visible map area

The typical solution for taking a screenshot in Windows doesn't solve my request

https://stackoverflow.com/questions/2846947/get-screenshot-on-windows-with-python

although in Pyscreenshot v2.3 I can define the rough bounds of my screen and capture them, how about if I change my QGIS window to another place

https://pypi.org/project/pyscreenshot/#files

Is there an option to capture the screenshot of the visible map in QGIS both by using PyGIS or maybe not programmatically (GRASS or sth?)

5
  • what was wrong with iface.mapCanvas().saveAsImage()? – JGH Mar 31 at 14:51
  • Traceback (most recent call last): File "C:\PROGRA~1\QGIS3~1.12\apps\Python37\lib\code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> AttributeError: 'QgsMapCanvas' object has no attribute 'mapRenderer' – MKR Mar 31 at 14:55
  • 1
    an answer is on this page? gis.stackexchange.com/questions/291545/… – Mapperz Mar 31 at 21:58
  • Yes, it's a good one! Thanks! The only one smallish thing that is irritating. Why along with my .png files I am getting the .pgw extension too? – MKR Apr 1 at 8:53
  • @Mapperz don't worry about it. I solved it by using the simply python script available here: stackoverflow.com/questions/32834731/… – MKR Apr 1 at 9:34
3

You may try the following to capture the QGIS main window area with all infos if you use "pyscreenshot"

from qgis.PyQt.QtGui import QScreen
import pyscreenshot as ImageGrab
from datetime import datetime

date = datetime.now()
filename = date.strftime('%Y-%m-%d_%H-%M-%S.jpg')
mainWin = iface.mainWindow()

x, y, w, h = mainWin.x(), mainWin.y(), mainWin.width(), mainWin.height()
bbox = (x, y, x + w, y + h)
# part of the screen
im = ImageGrab.grab(bbox=bbox)

# save image file
im.save(f"/tmp/{filename}.png")

# If you want a dialog box (above im.save can be commented in this case)
path, ok = QFileDialog.getSaveFileName(mainWin, "Save file", "", "Images (*.png *.jpg)");
if ok:
    im.save(path)

If you want only the map area, it should be

# Change the path
iface.mapCanvas().saveAsImage('/tmp/out.png')

# You can also use the following to reuse existing dialog for saving image
iface.actionSaveMapAsImage().trigger()
11
  • That's perfect! How can I add the "Save As" window pop-up? Is it: file_path = filedialog.asksaveasfilename(defaultextension='.png') myScreenshot.save(file_path)? – MKR Apr 1 at 9:03
  • Edited answer for this intent – ThomasG77 Apr 1 at 10:20
  • I am getting an error like this: Traceback (most recent call last): File "C:\PROGRA~1\QGIS3~1.12\apps\Python37\lib\code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> File "<string>", line 2, in <module> File "C:/PROGRA~1/QGIS3~1.12/apps/qgis/./python\qgis\utils.py", line 743, in _import mod = _builtin_import(name, globals, locals, fromlist, level) ModuleNotFoundError: No module named 'pyscreenshot' – MKR Apr 1 at 10:38
  • I used the second one frankly and it works well: iface.mapCanvas().saveAsImage(QFileDialog.getSaveFileName(mainWin, "Save file", "", "Images (*.png *.jpg)")) what I am missing is the DPI resolution for my image. – MKR Apr 1 at 10:43
  • For the first error, it's because you did not instal pyscreenshot module within the PyQGIS Python version – ThomasG77 Apr 1 at 11:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.