[Qgis-developer] How to use QPixmap argument in saveAsImage()

Martin Dobias wonder.sk at gmail.com
Tue Jan 26 06:35:38 EST 2010


On Tue, Jan 26, 2010 at 12:02 AM, Echavarria Gregory, Maria Angelica
<m.echavarriagregory at umiami.edu> wrote:
> Dear Devs:
>
> I am currently using self.canvas.saveAsImage ( FileName,  QPixmap=0,  QString="PNG" ) with only the first argument, the second and third are therefore using default settings. My Qgis version is OSGeo4W Kore 1.0, along with Python2.5.  I have tried many ways of using QPixmap following the API, with no success. I need to set up the resolution of my saved image (int width, int height, depth, ... or dpi if that option alone exists.) Currently, my images are being saved by default at 96 dpi which is very low for my purpose. Please, how are the syntax for using the second argument QPixmap? or... should I define QPixmap before and just call it in the method? how? please give me some exemplified advice.

Hi,

saveAsImage() method is meant to really just copy the contents of the
canvas, so if you'd like to work with higher resolution, you should
use the composer classes.

I'm attaching a sample code which I've just put together. When the
code is run from qgis python console, it renders layers from map
canvas with the current extent into a PNG file. The default settings
for composition are page size A4 and resolution 300 DPI (it's possible
to change them). The advantage with this (a bit more complicated)
approach is that you can use also PDF or PostScript output and you can
use further composer items available in map composer (scale bar,
legend, labels, ...) If you need further guidance with usage of
composition and/or composer items, Marco will be able to give you some
more guidance.

Martin



from qgis.core import *
from qgis.utils import iface
from PyQt4.QtCore import *
from PyQt4.QtGui import *

# set up composition
mapRenderer = iface.mapCanvas().mapRenderer()
c = QgsComposition(mapRenderer)
c.setPlotStyle(QgsComposition.Print)

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

# add a map to the composition
x, y = 0, 0
w, h = c.paperWidth(), c.paperHeight()
composerMap = QgsComposerMap(c, x,y,w,h)
c.addItem(composerMap)

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

# render the composition
imagePainter = QPainter(image)
sourceArea = QRectF(0, 0, c.paperWidth(), c.paperHeight())
targetArea = QRectF(0, 0, width, height)
c.render(imagePainter, targetArea, sourceArea)
imagePainter.end()

image.save("out.png", "png")


More information about the Qgis-developer mailing list