from
PIL
import
Image
import
sys, os
def
genData(data):
newd
=
[]
for
i
in
data:
newd.append(
format
(
ord
(i),
'08b'
))
return
newd
def
modPix(pix, data):
datalist
=
genData(data)
lendata
=
len
(datalist)
imdata
=
iter
(pix)
for
i
in
range
(lendata):
pix
=
[value
for
value
in
imdata.
next
()[:
3
]
+
imdata.
next
()[:
3
]
+
imdata.
next
()[:
3
]]
for
j
in
range
(
0
,
8
):
if
(datalist[i][j]
=
=
'0'
)
and
(pix[j]
%
2
!
=
0
):
if
(pix[j]
%
2
!
=
0
):
pix[j]
-
=
1
elif
(datalist[i][j]
=
=
'1'
)
and
(pix[j]
%
2
=
=
0
):
pix[j]
-
=
1
if
(i
=
=
lendata
-
1
):
if
(pix[
-
1
]
%
2
=
=
0
):
pix[
-
1
]
-
=
1
else
:
if
(pix[
-
1
]
%
2
!
=
0
):
pix[
-
1
]
-
=
1
pix
=
tuple
(pix)
yield
pix[
0
:
3
]
yield
pix[
3
:
6
]
yield
pix[
6
:
9
]
def
encode_enc(newimg, data):
w
=
newimg.size[
0
]
(x, y)
=
(
0
,
0
)
for
pixel
in
modPix(newimg.getdata(), data):
newimg.putpixel((x, y), pixel)
if
(x
=
=
w
-
1
):
x
=
0
y
+
=
1
else
:
x
+
=
1
def
encode(orgfilename, msg, outfilename):
img
=
orgfilename
image
=
Image.
open
(img,
'r'
)
data
=
msg
if
(
len
(data)
=
=
0
):
raise
ValueError(
'Data is empty'
)
newimg
=
image.copy()
encode_enc(newimg, data)
new_img_name
=
outfilename
newimg.save(new_img_name,
str
(new_img_name.split(
"."
)[
1
].upper()))
def
decode(filename):
img
=
filename
image
=
Image.
open
(img,
'r'
)
data
=
''
imgdata
=
iter
(image.getdata())
while
(
True
):
pixels
=
[value
for
value
in
imgdata.
next
()[:
3
]
+
imgdata.
next
()[:
3
]
+
imgdata.
next
()[:
3
]]
binstr
=
''
for
i
in
pixels[:
8
]:
if
(i
%
2
=
=
0
):
binstr
+
=
'0'
else
:
binstr
+
=
'1'
data
+
=
chr
(
int
(binstr,
2
))
if
(pixels[
-
1
]
%
2
!
=
0
):
print
data
return
data
def
printUsage():
print
" This program Encode / Decode hidden message into image."
print
" <Usage>"
print
" Encode: steg_test.py -a [input_filename] [message] [out_filename]"
print
" Decode: steg_test.py -b [out_filename]"
if
__name__
=
=
'__main__'
:
if
len
(sys.argv) <
3
:
printUsage()
exit(
0
)
if
sys.argv[
1
]
=
=
'-a'
:
if
len
(sys.argv)
=
=
5
:
encode(sys.argv[
2
], sys.argv[
3
], sys.argv[
4
])
else
:
printUsage()
elif
sys.argv[
1
]
=
=
'-b'
:
if
len
(sys.argv)
=
=
3
:
decode(sys.argv[
2
])
else
:
printUsage()
else
:
printUsage()