import static qupath.lib.roi.PathROIToolsAwt.getShape;
import java.awt.image.BufferedImage
import java.awt.Color
import javax.imageio.ImageIO
import qupath.lib.projects.ProjectIO
import qupath.lib.scripting.QPEx
// select the folder to save the annotations
def directory = getQuPath().getDialogHelper().promptForDirectory(null)
// List of annotations
def annotationNames = []
for (annotation in getAnnotationObjects()) {
//print(annotation.getPathClass())
annotationNames.push(annotation.getPathClass())
annotationNames.unique()
}
// Loop over each annotation type
for (def annotationName in annotationNames)
{
// Get the annotation objects of this type
def annotationType = getPathClass( annotationName.toString())
def annotations = getAnnotationObjects()
def annotationsToSave = annotations.findAll({annotation -> annotation.getPathClass() == annotationType})
def shapes = annotationsToSave.collect {getShape(it.getROI())}
// Create a grayscale image, here it's 10% of the full image size
double downsample = 10.0
def server = getCurrentImageData().getServer()
int w = (server.getWidth() / downsample) as int
int h = (server.getHeight() / downsample) as int
def img = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY)
// Paint the shapes (this is just 'standard' Java - you might want to modify)
def g2d = img.createGraphics()
g2d.scale(1.0/downsample, 1.0/downsample)
g2d.setColor(Color.WHITE)
for (shape in shapes)
g2d.fill(shape)
g2d.dispose()
// Save the result
def imageName = server.getShortServerName()
String name = String.format("%s_%s.png", imageName, annotationName)
def outputFile = new File(directory, name)
ImageIO.write(img, 'PNG', outputFile)
}