def _generate_image(self, matrix, width, height, padding, foreground, background, image_format):
        image = Image.new("RGBA", (width + padding[2] + padding[3], height + padding[0] + padding[1]), background)
        draw = ImageDraw.Draw(image)
        block_width = width // self.columns
        block_height = height // self.rows
        for row, row_columns in enumerate(matrix):
            for column, cell in enumerate(row_columns):
                if cell:
                    x1 = padding[2] + column * block_width
                    y1 = padding[0] + row * block_height
                    x2 = padding[2] + (column + 1) * block_width - 1
                    y2 = padding[0] + (row + 1) * block_height - 1
                    draw.rectangle((x1, y1, x2, y2), fill=foreground)
        stream = BytesIO()
        if image_format.upper() == "JPEG":
            image = image.convert(mode="RGB")
        try:
            image.save(stream, format=image_format, optimize=True)
        except KeyError:
            raise ValueError("Pillow does not support requested image format: %s" % image_format)
        image_raw = stream.getvalue()
        stream.close()
        return image_raw