python 二进制读写文件


#-*- coding: utf-8 -*-

f = open('f:/text.bmp','rb')
filedata = f.read()
filesize = f.tell()
f.close()
filedata2 = bytearray(filedata)
width = filedata2[18]
height = filedata2[22]
print('width:', width)
print('height:', height) # less than 255 , width and height have 4 bytes
print('pix:', width * height)
print('filesize:', filesize)
f2 = open('f:/t2.bmp','wb')
change = 0
index = 54
loop = 0
while index < filesize - 2:
    loop += 1
    r = filedata2[index] 
    g = filedata2[index+1]
    b = filedata2[index+2]
    threshold = 110
    if (r < threshold) and (g < threshold) and (b < threshold):
        bytes = bytearray(3)
        bytes[0] = 0
        bytes[1] = 255
        bytes[2] = 0
        filedata2[index:index+3] = bytes
    else:
        bytes = bytearray(3)
        bytes[0] = bytes[1] = bytes[2] = 255
        filedata2[index:index+3] = bytes
        change += 1
    index += 3

f2.write(filedata2)
f2.close()
print ('change:',change)
print ('loop:',loop)

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM