0

I would like to use Python to change the DPI of my map image files, I am not sure where in my code I need to add this line.

from qgis.core import QgsProject
from qgis.core import QgsPrintLayout
from qgis.core import QgsLayoutExporter
from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
                       QgsFeatureSink,
                       QgsProcessingException,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterFeatureSink,
                       QgsLayoutSize
                       )
from qgis import processing


project = QgsProject.instance()             
manager = project.layoutManager()           
layout = QgsPrintLayout(project)          
layoutName = "PrintLayout"

layouts_list = manager.printLayouts()
for layout in layouts_list:
    if layout.name() == layoutName:
        manager.removeLayout(layout)
        
layout = QgsPrintLayout(project)
layout.initializeDefaults()               
layout.setName(layoutName)
manager.addLayout(layout)

from datetime import datetime

today = datetime.today().strftime('%Y-%m-%d')


manager = QgsProject.instance().layoutManager()     


countrylist = ['Africa', 'Asia', 'Caribbean', 'World map', 'Europe', 'Middle East', 'Oceania', 'South America', 'North America']

for i in countrylist:
    layout = manager.layoutByName(f'{i}')        
    exporter = QgsLayoutExporter(layout)
    exporter.exportToImage(f'D:/Sanch/Work/Automate/{today} {i}.png', QgsLayoutExporter.ImageExportSettings()) 

1 Answer 1

1

You can create a settings object which accesses the ImageExportSettings of the QgsLayoutExporter object. You can then modify the attributes of the settings object as desired, and pass it as the second argument to the exportToImage() method. See below for a minimal example (in your case you would declare the settings object and set its attributes inside your for loop).

project = QgsProject().instance()
manager = project.layoutManager()
layout = manager.layoutByName('layout_name')

exporter = QgsLayoutExporter(layout)
settings = exporter.ImageExportSettings()
settings.dpi = 150

path = 'C:\\Users\\Username\\Desktop\\test_layout_image.png'

exporter.exportToImage(path, settings)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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