0

I have a user inputted binary string and an image. I'm trying to encode my string inside of my image by changing the red values of pixels slightly. I want to encode my string in my image from top to bottom, left to right, with 1 character of the string in each red component of the pixel. If the character is '1', then I want to increase the red pixel by 1. If if the character is '0', then I want to decrease the red component by 1. Here is my code so far:

from PIL import Image

x = input ("Enter a message to encode: ")
print("You entered: " + x)
z = bin(int.from_bytes(x.encode(), 'big'))
print(z)
z = z[2:]

im = Image.open('1.jpg')
pixelMap = im.load()
img = Image.new( im.mode, im.size)
pixelsNew = img.load()
for i in range(img.size[0]):
    for j in range(img.size[1]):
        for y in z:
            if y == 1:
                # set red component +1
            if y == 0:
                # set red component -1
img.show()

I know that I can edit a RGB pixel like this:

pixelsNew[i, j] = (0, 0, 0)

But how can I edit the existing pixel's red component instead of creating a new pixel? Something like this:

pixelsNew[i, j] = (R+1, G, B)
K. Hall
  • 169
  • 2
  • 11
  • 1
    https://stackoverflow.com/questions/49280402/python-change-the-rgb-values-of-the-image-and-save-as-a-image this might be helpful. – Sammit Aug 09 '19 at 04:33
  • 1
    As a first step, stop using JPEG if you expect to accurately read back what you write to disk. JPEG is **lossy** - it changes pixels to save space! – Mark Setchell Aug 10 '19 at 20:12
  • 1
    You can do exactly like you want to do it, as long as you set your variables before you use them: `R, G, B = pixelsNew[i, j]`. Your code doesn't particularly look performant or robust, but it should work. – physicalattraction Aug 11 '19 at 15:45

0 Answers0