Python 更改base64字符串并将其保存为图像

Python 更改base64字符串并将其保存为图像,python,image-processing,base64,Python,Image Processing,Base64,我正在用python将一个图像转换为base64字符串,将其转换为一个列表,对几个字符进行更改,然后将base64字符串转换回图像 这样做的目的是创造出小故障艺术,在这种艺术中,图像编码的微小变化可以产生一定的效果 这就是我的代码的样子: import base64 import random import string times = 0 with open(r"C:\Users\Justin\Desktop\image.jpg", "rb") as image: text = ba

我正在用python将一个图像转换为base64字符串,将其转换为一个列表,对几个字符进行更改,然后将base64字符串转换回图像

这样做的目的是创造出小故障艺术,在这种艺术中,图像编码的微小变化可以产生一定的效果

这就是我的代码的样子:

import base64
import random
import string

times = 0
with open(r"C:\Users\Justin\Desktop\image.jpg", "rb") as image:
    text = base64.b64encode(image.read())
text = str(text)
text = list(text)
char_no = len(text)
while True:
    crpt_amn = input("how much do you want to corrupt the image? insert a value from 0 to " + str(char_no) + " ")
    try:
      if int(crpt_amn) < 0:
          print("value is out of range!")
      elif int(crpt_amn) > char_no:
          print("value is out of range!")
      else:
          break          
    except ValueError:
          print("that isn't a number")
while times < (int(crpt_amn) + 1):
    picked = random.randint(0, char_no)
    if text[picked] == '/':
        times += 1
    else:
        text[picked] = random.choice(string.ascii_letters)
        times += 1    
text = ''.join(text)
text = str.encode(text)
text = base64.b64decode(text)
filename = "out_img.jpg"
with open(filename, "wb") as picture:
    picture.write(text)
但输出图像仍然无法打开

是否有任何方法可以实现所需的功能,用户可以将base64字符串作为列表进行编辑

谢谢大家!


(很抱歉,如果我把一些术语弄错了,或者我的问题看起来很荒谬,我仍然是python的初学者)

base64不能在编辑时以您喜欢的方式进行更改。。。您不仅需要确保只输入合法的base64字符,还需要确保长度保持不变,因为base64每字节工作6/8位,因此当输入增加1个字符时,输出可以增加1个字符或2个字符。。。你真的应该只使用base16,它更容易通过ITA转换成二进制和从二进制转换成二进制,还有反物质胺提到的破坏base64数据的问题,还有更大的破坏JPEG文件结构的问题。如果要对像素执行随机操作,则需要从图像文件中提取像素数据,例如使用PIL。忘记base64的东西吧,您可以直接修改原始RGB
bytes
数据。然后将其传递回PIL以构建一个新的JPEG。同时,我建议您学习一下Unicode编码。许多年前,Stack Overflow联合创始人乔尔·斯波尔斯基(Joel Spolsky)写了一篇伟大的文章:这篇文章仍然值得一读。另请参见Python。
import base64
import random
import string

with open(r"C:\Users\Justin\Desktop\image.jpg", "rb") as image:
    text = base64.b64encode(image.read())
text = str(text)
text = str.encode(text)
text = base64.b64decode(text)
filename = "out_img.jpg"
with open(filename, "wb") as picture:
    picture.write(text)