• 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)
    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)
    

      

  • 相关阅读:
    python多进程(一)
    python操作memcached
    python操作redis
    SQLAlchemy总结
    SQLAlchemy-ORM
    python操作mysql二
    python操作mysql
    python正则二
    python正则
    python内置模块(三)
  • 原文地址:https://www.cnblogs.com/ezhong/p/3529202.html
Copyright © 2020-2023  润新知