noumanjavaid commited on
Commit
dbea623
·
verified ·
1 Parent(s): 9b9ff61

Update utils.py

Browse files
Files changed (1) hide show
  1. utils.py +80 -68
utils.py CHANGED
@@ -4,29 +4,6 @@ from PIL import Image, PngImagePlugin
4
  import os
5
  import uuid
6
 
7
- def png_encode(im_name, extra):
8
- try:
9
- im = Image.open(im_name)
10
- info = PngImagePlugin.PngInfo()
11
- info.add_text("TXT", extra)
12
-
13
- unique_id = str(uuid.uuid4())[:8]
14
- filename, ext = os.path.splitext(im_name)
15
- new_filename = f"{filename}_{unique_id}{ext}"
16
- im.save(new_filename, pnginfo=info)
17
-
18
- width, height = im.size
19
- rect_width, rect_height = 200, 50
20
- x = width - rect_width - 10
21
- y = height - rect_height - 10
22
- png_encode_coords = (x, y, rect_width, rect_height)
23
-
24
- return new_filename, "", png_encode_coords
25
-
26
- except Exception as e:
27
- return None, str(e), None
28
-
29
-
30
  def to_bin(data):
31
  if isinstance(data, str):
32
  return ''.join([format(ord(i), "08b") for i in data])
@@ -39,62 +16,97 @@ def to_bin(data):
39
  else:
40
  raise TypeError("Type not supported.")
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- def decode(image_name, txt=None):
44
  try:
45
- BGRimage = cv2.imread(f"{image_name}")
46
- image = cv2.cvtColor(BGRimage, cv2.COLOR_BGR2RGB)
 
 
 
47
  binary_data = ""
48
  for row in image:
49
  for pixel in row:
50
- r, g, b = to_bin(pixel)
51
- binary_data += r[-1]
52
- binary_data += g[-1]
53
- binary_data += b[-1]
54
  all_bytes = [binary_data[i: i + 8] for i in range(0, len(binary_data), 8)]
55
  decoded_data = ""
56
  for byte in all_bytes:
57
  decoded_data += chr(int(byte, 2))
58
  if decoded_data[-5:] == "=====":
59
  break
60
- this = decoded_data[:-5].split("#####", 1)[0]
61
- return this
 
62
  except Exception as e:
63
- return str(e)
64
 
 
 
 
 
 
65
 
66
- def encode(image_name, secret_data, txt=None):
67
- msg = ""
68
- BGRimage = cv2.imread(f"{image_name}")
69
- image = cv2.cvtColor(BGRimage, cv2.COLOR_BGR2RGB)
70
- n_bytes = image.shape[0] * image.shape[1] * 3 // 8
71
- print("[*] Maximum bytes to encode:", n_bytes)
72
- secret_data1 = secret_data
73
- while True:
74
- if len(secret_data1) + 5 < (n_bytes):
75
- secret_data1 = f'{secret_data1}#####'
76
- elif len(secret_data1) + 5 >= (n_bytes):
77
- break
78
- secret_data = secret_data1
79
- if len(secret_data) > n_bytes:
80
- msg = "Watermark is too large for Image Size"
81
- return image_name, msg
82
- secret_data += "====="
83
- data_index = 0
84
- binary_secret_data = to_bin(secret_data)
85
- data_len = len(binary_secret_data)
86
- for row in image:
87
- for pixel in row:
88
- r, g, b = to_bin(pixel)
89
- if data_index < data_len:
90
- pixel[0] = int(r[:-1] + binary_secret_data[data_index], 2)
91
- data_index += 1
92
- if data_index < data_len:
93
- pixel[1] = int(g[:-1] + binary_secret_data[data_index], 2)
94
- data_index += 1
95
- if data_index < data_len:
96
- pixel[2] = int(b[:-1] + binary_secret_data[data_index], 2)
97
- data_index += 1
98
- if data_index >= data_len:
99
- break
100
- return image, msg
 
4
  import os
5
  import uuid
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  def to_bin(data):
8
  if isinstance(data, str):
9
  return ''.join([format(ord(i), "08b") for i in data])
 
16
  else:
17
  raise TypeError("Type not supported.")
18
 
19
+ def encode(image_path, secret_data):
20
+ try:
21
+ # Read the image
22
+ image = cv2.imread(image_path)
23
+ if image is None:
24
+ return None, "Failed to read image"
25
+
26
+ # Calculate maximum bytes for encoding
27
+ n_bytes = image.shape[0] * image.shape[1] * 3 // 8
28
+
29
+ # Check if the secret data is too large
30
+ secret_data_with_delimiter = f'{secret_data}#####'
31
+ if len(secret_data_with_delimiter) + 5 >= n_bytes:
32
+ return None, "Watermark is too large for Image Size"
33
+
34
+ # Add ending delimiter
35
+ secret_data_with_delimiter += "====="
36
+
37
+ # Convert data to binary
38
+ binary_secret_data = to_bin(secret_data_with_delimiter)
39
+ data_len = len(binary_secret_data)
40
+ data_index = 0
41
+
42
+ # Encode the data into the image
43
+ for i in range(image.shape[0]):
44
+ for j in range(image.shape[1]):
45
+ pixel = image[i, j]
46
+ for color_channel in range(3):
47
+ if data_index < data_len:
48
+ # Get the binary value of the pixel
49
+ binary_value = to_bin(pixel[color_channel])
50
+ # Replace the least significant bit
51
+ new_binary = binary_value[:-1] + binary_secret_data[data_index]
52
+ # Update the pixel with the new value
53
+ pixel[color_channel] = int(new_binary, 2)
54
+ data_index += 1
55
+ image[i, j] = pixel
56
+ if data_index >= data_len:
57
+ break
58
+ if data_index >= data_len:
59
+ break
60
+
61
+ return image, None
62
+ except Exception as e:
63
+ return None, f"Error during encoding: {str(e)}"
64
 
65
+ def decode(image_path):
66
  try:
67
+ # Read the image
68
+ image = cv2.imread(image_path)
69
+ if image is None:
70
+ return "Failed to read image"
71
+
72
  binary_data = ""
73
  for row in image:
74
  for pixel in row:
75
+ for color_channel in pixel:
76
+ binary_data += to_bin(color_channel)[-1]
77
+
78
+ # Convert binary to text
79
  all_bytes = [binary_data[i: i + 8] for i in range(0, len(binary_data), 8)]
80
  decoded_data = ""
81
  for byte in all_bytes:
82
  decoded_data += chr(int(byte, 2))
83
  if decoded_data[-5:] == "=====":
84
  break
85
+
86
+ # Remove delimiters
87
+ return decoded_data[:-5].split("#####")[0]
88
  except Exception as e:
89
+ return f"Error during decoding: {str(e)}"
90
 
91
+ def png_encode(im_name, extra):
92
+ try:
93
+ im = Image.open(im_name)
94
+ info = PngImagePlugin.PngInfo()
95
+ info.add_text("TXT", extra)
96
 
97
+ unique_id = str(uuid.uuid4())[:8]
98
+ filename, ext = os.path.splitext(im_name)
99
+ new_filename = f"{filename}_{unique_id}{ext}"
100
+ im.save(new_filename, "PNG", pnginfo=info)
101
+
102
+ width, height = im.size
103
+ rect_width, rect_height = 200, 50
104
+ x = width - rect_width - 10
105
+ y = height - rect_height - 10
106
+ global png_encode_coords
107
+ png_encode_coords = (x, y, rect_width, rect_height)
108
+
109
+ return new_filename, None
110
+
111
+ except Exception as e:
112
+ return None, str(e)