Skip to content

Instantly share code, notes, and snippets.

@ksss
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ksss/c08547948f672d03a9e5 to your computer and use it in GitHub Desktop.
Save ksss/c08547948f672d03a9e5 to your computer and use it in GitHub Desktop.
split exif and other form .jpg image
#! /usr/bin/env ruby
# ruby strip_exif.rb [input.jpg] [output.jpg]
require 'stringio'
io = nil
in_path = ARGV[0]
out_path = ARGV[1]
File.open(in_path, 'rb') do |rf|
io = StringIO.new(rf.read)
end
if io.read(2) != "\xFF\xD8".b
fail "not jpeg image"
end
def io.readframe
field_marker = read(2).unpack("C2")
fail 'field format error' unless field_marker[0] == 0xFF
frame_size = read(2).unpack("C2").inject(0){|r,v|
r = r << 8
r += v
}
[field_marker[1], read(frame_size - 2)]
end
def io.read_to_field(field)
loop do
marker, frame = readframe
case marker
when field
return frame
when 0xDA # sos
fail "FF#{field.to_s(16)} not found"
else
# ignore
end
end
end
marker, frame = io.readframe
fail 'not jfif' unless marker == 0xE0
exif = io.read_to_field(0xE1) # app1
after_exif_pos = io.pos
io.rewind
File.open(out_path, 'wb+') do |wf|
wf.write(io.read(after_exif_pos - (exif.length+4))) # 4 = field_marker(2)+size(2)
io.pos = after_exif_pos
wf.write(io.read)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment