Skip to content

Instantly share code, notes, and snippets.

@jason-s
Created October 21, 2014 15:43
Show Gist options
  • Save jason-s/3ca3abb51e2daf3f51b5 to your computer and use it in GitHub Desktop.
Save jason-s/3ca3abb51e2daf3f51b5 to your computer and use it in GitHub Desktop.
Add DPI to PNG files
'''
Copyright 2014 Jason M. Sachs
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
import struct
import binascii
def add_phys_chunk(filename, dpi):
with open(filename,'rb') as f:
raw = f.read()
phys_chunk_hdr = 'pHYs'
dpmeter = int(dpi / 0.0254)
phys_chunk_data = (struct.pack('>I',dpmeter)*2) + '\x01'
phys_chunk_crc = binascii.crc32(phys_chunk_hdr+phys_chunk_data)
phys_chunk = (struct.pack('>i',len(phys_chunk_data))
+ phys_chunk_hdr
+ phys_chunk_data
+ struct.pack('>i',phys_chunk_crc))
out = raw[:33] + phys_chunk + raw[33:]
with open(filename,'wb') as f:
f.write(out)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment