-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtiffTools.py
More file actions
executable file
·372 lines (289 loc) · 12.5 KB
/
Copy pathtiffTools.py
File metadata and controls
executable file
·372 lines (289 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
#!/usr/bin/env python3
# TIFF tools utilizing paps, gs, convert, tiffset, Pillow (PIL) and more
#
# by Magnetic-Fox, 19.04.2025 - 07.09.2026
#
# (C)2025-2026 Bartłomiej "Magnetic-Fox" Węgrzyn
import os
import io
import math
import shutil
import tempfile
import subprocess
import PIL.Image
# Get image size function
def getImageSize(imageData):
img = PIL.Image.open(io.BytesIO(imageData))
width = img.width
height = img.height
img.close()
return width, height
# Function for gathering image count in one file
def getImageCount(filename):
img = PIL.Image.open(filename)
imgCount = img.n_frames
img.close()
return imgCount
# Image data to non-G3 TIFF data converter
def imageDataToTIFF(imageData, pageWidth = 1728, marginLeft = 32, marginRight = 32):
# Get image size to test if image has to be rotated
width, height = getImageSize(imageData)
# Prepare command
convertCommand = ["convert", "-"]
# Set to rotate if needed
if width > height:
convertCommand += ["-rotate", "90"]
# Below should give such result for resize (on default values): 1664x
convertCommand += ["-resize", str(pageWidth - marginLeft - marginRight) + "x"]
convertCommand += ["-background", "white", "-alpha", "remove", "-gravity", "northwest", "-splice", str(marginLeft) + "x0"]
convertCommand += ["-background", "white", "-alpha", "remove", "-gravity", "northeast", "-splice", str(marginRight) + "x0"]
convertCommand += ["tiff:-"]
# Convert images to TIFFs with auto-size and auto-margin
convert = subprocess.Popen(convertCommand, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
return convert.communicate(imageData)[0]
# Image file to non-G3 TIFF file converter (wrapper)
def imageToTIFF(imageFileName, tiffFileName, pageWidth = 1728, marginLeft = 32, marginRight = 32):
imageFile = open(imageFileName, "rb")
imageData = imageFile.read()
imageFile.close()
tiffData = imageDataToTIFF(imageData, pageWidth, marginLeft, marginRight)
tiffFile = open(tiffFileName, "wb")
tiffFile.write(tiffData)
tiffFile.close()
return
# Text to TIFF renderer (0 - standard resolution, 1 - fine resolution, 2 - super fine resolution)
#
# Default bottom margin value explanation:
# 141 PS points of bottom margin were chosen to achieve 2000 px height for image after cutting
# using cutter procedure (which has its default bottom margin set to 94 pixels).
#
# Why?
# 196 pixels per inch is the base document vertical resolution for G3 fax produced by GhostScript.
# 1 PostScript point is 1/72 inch, which means that 72 PostScript points gives us 196 pixels.
# Default page height for 196 DPI is 2289 pixels, which gives us 289 too much (we want 2000).
# Cutter utility needs additional 94 pixels to provide default bottom margin, so we need to add this too.
# Now: 289 + 94 (default from cutter) gives us 383 pixels we want out.
# This gives us such formula: bottomMargin = (72 * 383) / 196, which we have to ceil (to not exceed 2000 pixels!)
#
# Why 2000 pixels?
# That's because mgetty-fax will automatically scale images that exceeds such height.
# I just wanted to avoid it. ;)
def textToTIFF(tiffFileName, textData, resolution = 1, fontNameAndSize = "Monospace 10", topMargin = 6, bottomMargin = 141):
# Prepare paps and gs commands
papsCommand = ["paps", "--font=" + fontNameAndSize, "--top-margin=" + str(topMargin), "--bottom-margin=" + str(bottomMargin)]
ghscCommand = ["gs", "-sDEVICE=tiffg3"]
# Super fine resolution
if resolution == 2:
ghscCommand += ["-r204x391"]
# Fine resolution ("normal"); use also for standard (98 dpi) resolution
else:
ghscCommand += ["-r204x196"]
ghscCommand += ["-sOutputFile=" + tiffFileName, "-dBATCH", "-dNOPAUSE", "-dSAFER", "-dQUIET", "-"]
# Create processes
paps = subprocess.Popen(papsCommand, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
ghsc = subprocess.Popen(ghscCommand, stdin = subprocess.PIPE)
# Pass text (encoded to the bytes type) to paps command and pass got postscript to gs command
postScript = paps.communicate(textData.encode())[0]
ghsc.communicate(postScript)
# Standard resolution resize (196 dpi -> 98 dpi)
if resolution == 0:
resizeAndApplyResolution(tiffFileName, resolution)
return
# Text file to TIFF renderer (wrapper)
def textFileToTIFF(tiffFileName, textFileName, resolution = 1, fontNameAndSize = "Monospace 10", topMargin = 6, bottomMargin = 141):
textFile = open(textFileName, "r")
textToTIFF(tiffFileName, textFile.read(), resolution, fontNameAndSize, topMargin, bottomMargin)
textFile.close()
return
# Resizer and DPI information applier (0 - standard resolution, 1 - fine resolution, 2 - super fine resolution)
def resizeAndApplyResolution(tiffFileName, resolution):
# Prepare main convert and tiffset commands
convertCommand = ["convert", tiffFileName]
tiffSetCommand = ["tiffset", "-s", "283"]
# Standard resolution - shrink image vertically (0.5x) and set vertical DPI to 98
if resolution == 0:
convertCommand += ["-resize", "100%x50%"]
tiffSetCommand += ["98.0"]
# Super fine resolution - enlarge image vertically (2x) and set vertival DPI to 391
elif resolution == 2:
convertCommand += ["-resize", "100%x200%"]
tiffSetCommand += ["391.0"]
# Fine resolution - no resize, but set vertical DPI to 196
else:
# Resizing not needed, so no convert command
tiffSetCommand += ["196.0"]
# Add TIFF file name to the both commands
convertCommand += [tiffFileName]
tiffSetCommand += [tiffFileName]
# Additional tiffsets before the main part (make space for DPI information and set horizontal DPI to 204)
subprocess.run(["tiffset", "-s", "296", "2", tiffFileName])
subprocess.run(["tiffset", "-s", "282", "204.0", tiffFileName])
# Resize TIFF
if resolution != 1:
subprocess.run(convertCommand)
# Apply vertical DPI information
subprocess.run(tiffSetCommand)
return
# Function for applying DPI information to the TIFF file (0 - standard, 1 - fine, 2 - super fine)
def applyDPIInformation(tiffFileName, resolution = 1):
# Prepare main tiffset command
tiffSetCommand = ["tiffset", "-s", "283"]
# Standard resolution
if resolution == 0:
tiffSetCommand += ["98.0"]
# Super fine resolution
elif resolution == 2:
tiffSetCommand += ["391.0"]
# Fine resolution
else:
tiffSetCommand += ["196.0"]
# Add file name
tiffSetCommand += [tiffFileName]
# Additional tiffsets before the main part (make space for DPI information and set horizontal DPI to 204)
subprocess.run(["tiffset", "-s", "296", "2", tiffFileName])
subprocess.run(["tiffset", "-s", "282", "204.0", tiffFileName])
# Main tiffset
subprocess.run(tiffSetCommand)
return
# Geometry recalculation function
def recalculateGeometry(geometryData, resolution = 1):
# Unpack geometry data
geometryData = geometryData.split("+")[1:]
geometryData[0] = int(geometryData[0])
geometryData[1] = int(geometryData[1])
# Recalculate
if resolution == 0:
geometryData[1] = math.ceil(geometryData[1] / 2)
elif resolution == 2:
geometryData[1] *= 2
# Combine and return geometry information
return "+" + str(geometryData[0]) + "+" + str(geometryData[1])
# Scale (non-interpolated resize) fine image data to chosen resolution
def scaleToResolution(inputData, resolution):
# To standard resolution
if resolution == 0:
return subprocess.Popen(["convert", "-", "-scale", "100%x50%", "-"], stdin = subprocess.PIPE, stdout = subprocess.PIPE).communicate(inputData)[0]
# To super fine resolution
elif resolution == 2:
return subprocess.Popen(["convert", "-", "-scale", "100%x200%", "-"], stdin = subprocess.PIPE, stdout = subprocess.PIPE).communicate(inputData)[0]
# To fine resolution
else:
# No conversion at all
return inputData
# Picture place function
def placePicture(inputFileName, outputFileName, pictureToPlaceData, pictureToPlacePosition, pictureToPlaceGeometry):
convertCommand = [ "convert", inputFileName,
"-", "-gravity", pictureToPlacePosition, "-geometry", pictureToPlaceGeometry, "-composite",
outputFileName ]
convert = subprocess.Popen(convertCommand, stdin = subprocess.PIPE)
convert.communicate(pictureToPlaceData)
return
# Picture place function (file-only version)
def placePictureFile(inputFileName, outputFileName, pictureToPlaceFile, pictureToPlacePosition, pictureToPlaceGeometry):
convertCommand = [ "convert", inputFileName,
pictureToPlaceFile, "-gravity", pictureToPlacePosition, "-geometry", pictureToPlaceGeometry, "-composite",
outputFileName ]
subprocess.run(convertCommand)
return
# TIFF to G3 converter
def TIFFtoG3(tiffFile, G3File):
g3file = open(G3File, "wb")
tifftopnm = subprocess.Popen(["tifftopnm", tiffFile], stdout = subprocess.PIPE)
pgmtopbm = subprocess.Popen(["pgmtopbm"], stdin = tifftopnm.stdout, stdout = subprocess.PIPE)
pbm2g3 = subprocess.run(["pbm2g3"], stdin = pgmtopbm.stdout, stdout = g3file)
g3file.close()
return
# Note for imageToG3TIFF - why default page height is 2000 pixels?
# It's because of MGetty's internal height value. If the image is less or equal 2000 pixels,
# then it won't be scaled, which of course means best possible quality while sending fax.
# Image data to G3 TIFF file converter (resolution data to apply: 0 - standard, 1 - fine, 2 - super fine)
def imageToG3TIFF(imageData, tiffFileName, resolution = 1, pageWidth = 1728, pageHeight = 2000, marginLeft = 32, marginRight = 32):
# Initial convert (with rotation)
nonG3TIFFData = imageDataToTIFF(imageData, pageWidth, marginLeft, marginRight)
# Get converted image size
width, height = getImageSize(nonG3TIFFData)
# If image height is greater than chosen page height, then resize it and center (keep page width)
if height > pageHeight:
convertCommand = [ "convert", "-",
"-background", "white",
"-alpha", "remove",
"-resize", "x" + str(pageHeight),
"-gravity", "center",
"-extent", str(pageWidth) + "x",
"pnm:-" ]
convert = subprocess.Popen(convertCommand, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
pnmData = convert.communicate(nonG3TIFFData)[0]
# If image height is less or equal chosen page height, just convert it to the PNM format
else:
convertCommand = [ "convert", "-",
"-background", "white",
"-alpha", "remove",
"pnm:-" ]
convert = subprocess.Popen(convertCommand, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
pnmData = convert.communicate(nonG3TIFFData)[0]
# Convert PNM data to PBM
ppmtopgmCommand = ["ppmtopgm"]
pgmtopbmCommand = ["pgmtopbm"]
ppmtopgm = subprocess.Popen(ppmtopgmCommand, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
pgmtopbm = subprocess.Popen(pgmtopbmCommand, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
pgmData = ppmtopgm.communicate(pnmData)[0]
pbmData = pgmtopbm.communicate(pgmData)[0]
# Open file to save G3 TIFF data
tiffFile = open(tiffFileName, "wb")
# Convert PBM to G3 TIFF
pnmtotiffCommand = ["pnmtotiff", "-g3"]
pnmtotiff = subprocess.Popen(pnmtotiffCommand, stdin = subprocess.PIPE, stdout = tiffFile)
pnmtotiff.communicate(pbmData)
# Close file
tiffFile.close()
# Apply DPI information to the TIFF file
applyDPIInformation(tiffFileName, resolution)
return
# Image file to G3 TIFF file converter (wrapper)
def imageFileToG3TIFF(imageFileName, tiffFileName, resolution = 1, pageWidth = 1728, pageHeight = 2000, marginLeft = 32, marginRight = 32):
imageFile = open(imageFileName, "rb")
imageData = imageFile.read()
imageFile.close()
imageToG3TIFF(imageData, tiffFileName, resolution, pageWidth, pageHeight, marginLeft, marginRight)
return
# Function for unpacking multipage TIFF files and place them in the current working directory
def unpackMultipageTIFF(filename, toFile = False, counter = 1):
newFileList = []
tiffList = []
try:
# Prepare another temporary directory and change directory to it
oldDir = os.getcwd()
dir = tempfile.TemporaryDirectory()
os.chdir(dir.name)
# Split TIFF image
tiffSplitCommand = ["tiffsplit", filename]
subprocess.run(tiffSplitCommand)
# Get and sort single TIFF files
fileList = os.listdir(".")
fileList.sort()
# If chosen to export to files, then move unpacked TIFFs to to current working directory
if toFile:
# Rename files according to the counter and move to the main temporary directory
for file in fileList:
shutil.move(file, oldDir + "/" + str(counter) + ".tiff")
newFileList += [str(counter) + ".tiff"]
counter += 1
# Otherwise
else:
# Read all files to the memory (do not move)
for file in fileList:
tiffFile = open(file, "rb")
tiffList += [tiffFile.read()]
tiffFile.close()
finally:
# Change back directory and clean up temporary directory
os.chdir(oldDir)
dir.cleanup()
# If chosen to export to files
if toFile:
# Return list of additional files
return newFileList
# Otherwise
else:
# Return list of TIFF files data
return tiffList