Skip to content

Commit 3e6b3b4

Browse files
Merge pull request #1938 from OfficialAhmed/master
ADDED NEW FEATURES (image2pdf.py)
2 parents ae8681c + d8527e1 commit 3e6b3b4

File tree

2 files changed

+110
-19
lines changed

2 files changed

+110
-19
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ Feel free to explore the scripts and use them for your learning and automation n
1414

1515
1. [batch_file_rename.py](https://github.com/geekcomputers/Python/blob/master/batch_file_rename.py) - Batch rename a group of files in a specified directory, changing their extensions.
1616
2. [create_dir_if_not_there.py](https://github.com/geekcomputers/Python/blob/master/create_dir_if_not_there.py) - Check if a directory exists in the user's home directory. Create it if it doesn't exist.
17-
3. [Fast Youtube Downloader](https://github.com/geekcomputers/Python/blob/master/youtube-downloader%20fast.py) - Download YouTube videos quickly with parallel threads using aria2c.
17+
3. [Fast Youtube Downloader](https://github.com/geekcomputers/Python/blob/master/youtubedownloader.py) - Download YouTube videos quickly with parallel threads using aria2c.
1818
4. [Google Image Downloader](https://github.com/geekcomputers/Python/tree/master/Google_Image_Downloader) - Query a given term and retrieve images from the Google Image database.
1919
5. [dir_test.py](https://github.com/geekcomputers/Python/blob/master/dir_test.py) - Test if the directory `testdir` exists. If not, create it.
2020
6. [env_check.py](https://github.com/geekcomputers/Python/blob/master/env_check.py) - Check if all the required environment variables are set.

image2pdf/image2pdf.py

+109-18
Original file line numberDiff line numberDiff line change
@@ -6,37 +6,128 @@ class image2pdf:
66
def __init__(self):
77
self.validFormats = (".jpg", ".jpeg", ".png", ".JPG", ".PNG")
88
self.pictures = []
9-
self.files = os.listdir()
10-
self.convertPictures()
11-
input("Done ..... (Press Any Key To Exit)")
9+
10+
self.directory = ""
11+
self.isMergePDF = True
1212

13+
14+
def getUserDir(self):
15+
""" Allow user to choose image directory """
16+
17+
msg = "\n1. Current directory\n2. Custom directory\nEnter a number: "
18+
user_option = int(input(msg))
19+
20+
# Restrict input to either (1 or 2)
21+
while user_option <= 0 or user_option >= 3:
22+
user_option = int(input(f"\n*Invalid input*\n{msg}"))
23+
24+
self.directory = os.getcwd() if user_option == 1 else input("\nEnter custom directory: ")
25+
1326
def filter(self, item):
1427
return item.endswith(self.validFormats)
1528

1629
def sortFiles(self):
17-
return sorted(self.files)
30+
return sorted(os.listdir(self.directory))
1831

1932
def getPictures(self):
2033
pictures = list(filter(self.filter, self.sortFiles()))
21-
if self.isEmpty(pictures):
22-
print(" [Error] there are no pictrues in the directory ! ")
23-
raise Exception(" [Error] there are no pictrues in the directory !")
24-
print("pictures are : \n {}".format(pictures))
34+
35+
if not pictures:
36+
print(f" [Error] there are no pictures in the directory: {self.directory} ")
37+
return False
38+
39+
print(f"Found picture(s) :")
2540
return pictures
2641

27-
def isEmpty(self, items):
28-
return True if len(items) == 0 else False
42+
def selectPictures(self, pictures):
43+
""" Allow user to manually pick each picture or merge all """
44+
45+
listedPictures = {}
46+
for index, pic in enumerate(pictures):
47+
listedPictures[index+1] = pic
48+
print(f"{index+1}: {pic}")
49+
50+
userInput = input("\n Enter the number(s) - (comma seperated/no spaces) or (A or a) to merge All \nChoice: ").strip().lower()
51+
52+
if userInput != "a":
53+
# Convert user input (number) into corresponding (image title)
54+
pictures = (
55+
listedPictures.get(int(number)) for number in userInput.split(',')
56+
)
57+
58+
self.isMergePDF = False
59+
60+
return pictures
2961

62+
3063
def convertPictures(self):
31-
for picture in self.getPictures():
32-
self.pictures.append(Image.open(picture).convert("RGB"))
33-
self.save()
64+
"""
65+
Convert pictures according the following:
66+
* If pictures = 0 -> Skip
67+
* If pictures = 1 -> use all
68+
* Else -> allow user to pick pictures
3469
35-
def save(self):
36-
self.pictures[0].save(
37-
"result.pdf", save_all=True, append_images=self.pictures[1:]
38-
)
70+
Then determine to merge all or one pdf
71+
"""
72+
73+
pictures = self.getPictures()
74+
totalPictures = len(pictures) if pictures else 0
75+
76+
if totalPictures == 0:
77+
return
78+
79+
elif totalPictures >= 2:
80+
pictures = self.selectPictures(pictures)
81+
82+
if self.isMergePDF:
83+
# All pics in one pdf.
84+
for picture in pictures:
85+
self.pictures.append(Image.open(f"{self.directory}\\{picture}").convert("RGB"))
86+
self.save()
87+
88+
else:
89+
# Each pic in seperate pdf.
90+
for picture in pictures:
91+
self.save(Image.open(f"{self.directory}\\{picture}").convert("RGB"), picture, False)
92+
93+
# Reset to default value for next run
94+
self.isMergePDF = True
95+
self.pictures = []
96+
print(f"\n{'#'*30}")
97+
print(" Done! ")
98+
print(f"{'#'*30}\n")
99+
100+
def save(self, image=None, title="All-PDFs", isMergeAll=True):
101+
# Save all to one pdf or each in seperate file
102+
103+
if isMergeAll:
104+
self.pictures[0].save(
105+
f"{self.directory}\\{title}.pdf",
106+
save_all=True,
107+
append_images=self.pictures[1:]
108+
)
109+
110+
else:
111+
image.save(f"{self.directory}\\{title}.pdf")
39112

40113

41114
if __name__ == "__main__":
42-
image2pdf()
115+
116+
# Get user directory only once
117+
process = image2pdf()
118+
process.getUserDir()
119+
process.convertPictures()
120+
121+
# Allow user to rerun any process
122+
while True:
123+
user = input("Press (R or r) to Run again\nPress (C or c) to change directory\nPress (Any Key) To Exit\nchoice:").lower()
124+
match user:
125+
case "r":
126+
process.convertPictures()
127+
case "c":
128+
process.getUserDir()
129+
process.convertPictures()
130+
case _:
131+
break
132+
133+

0 commit comments

Comments
 (0)