Skip to content

Commit c086c24

Browse files
authored
Merge pull request Python-World#113 from pranav6670/im_to_str_viceversa
Added Image to base64 convertor and vice-versa
2 parents 9d648d8 + 6ca3c15 commit c086c24

File tree

7 files changed

+63
-0
lines changed

7 files changed

+63
-0
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
.idea/
2+
.DS_Store
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Python script that converts Image to base64 encoding and vice versa.
2+
3+
4+
### Prerequisites
5+
* Required modules:
6+
```base64```, ```PIL```, ```skimage``` and ```cv2```
7+
* The ```base64``` is an inbuilt module.
8+
* Install ```PIL``` by running ```pip install Pillow```.
9+
* Install ```skimage``` by running ```pip install scikit-image```.
10+
* Install OpenCV by running ```pip install opencv-python```.
11+
12+
13+
### How to run the script
14+
First you need to go to the ImageStr_ViceVersa directory.
15+
16+
```cd Scripts/Miscellaneous/ImageStr_ViceVersa```
17+
* Select the image from your PC by providing its path to ```im_path``` variable.
18+
19+
And then run the following command once you are in project directory.
20+
21+
```python3 ImageStr_ViceVersa.py```
22+
23+
24+
### Screenshot
25+
26+
![Screenshot](Screenshot.png)
27+
28+
29+
30+
31+
## *Author Name*
32+
Pranav Natekar
Loading

Scripts/Miscellaneous/ImageStr_ViceVersa/base64_encoded.txt

+1
Large diffs are not rendered by default.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import base64
2+
from PIL import Image
3+
import io
4+
from skimage.metrics import structural_similarity
5+
import cv2
6+
7+
im_path = "test.jpg"
8+
# Convert to base64 encoding
9+
print("Encoding....")
10+
with open(im_path, "rb") as imageFile:
11+
base64_encoding = base64.b64encode(imageFile.read())
12+
# print(base64_encoding)
13+
14+
print("Decoding and writing to image...")
15+
# Write to the image
16+
f = io.BytesIO(base64.b64decode(base64_encoding))
17+
pilimage = Image.open(f)
18+
pilimage.save('image_from_encoding.jpg')
19+
print("Image saved!")
20+
21+
# Let's check for the structural similarity between original and generated image.
22+
original = cv2.imread('test.jpg', 0)
23+
generated = cv2.imread('image_from_encoding.jpg', 0)
24+
# Similarity index should be greater than 0.90
25+
similarity_index = structural_similarity(original, generated)
26+
print(F"Similarity index is {similarity_index}")
27+
28+
Loading
Loading

0 commit comments

Comments
 (0)