rbimg 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: a1c6d36ad031f09377de5a8d7b3ddd3288de61247281e030a443f01f6091fee1
4
+ data.tar.gz: 8742e79c6a0b56309c46f99bf40b8b8c91788f299dee77012e06b23af7acbe27
5
+ SHA512:
6
+ metadata.gz: e059f158f9b4d8a3da410d6009a9117f2b11f0b22452b4a55de8dbe59e28e1cf37f0ce9d5e366f5327507f7dc62e293c15a0a31fd8155ecd7daf1f79714ae9e2
7
+ data.tar.gz: 662a64d34818283e21ef1c10252a2ae3e665f3ba5776bbddfc5fecdc2f9120d15ff4ba71affb66938e8892ea8dd420af754f70e4d58a84f50af283d8abf523e7
data/.gitignore ADDED
@@ -0,0 +1,14 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ /data/
10
+ # rspec failure tracking
11
+ .rspec_status
12
+
13
+ *.png
14
+ test.rb
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.7.1
6
+ before_install: gem install bundler -v 2.1.4
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at micah.shute@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in rbimg.gemspec
4
+ gemspec
5
+
6
+ gem "rake", "~> 12.0"
7
+ gem "rspec", "~> 3.0"
8
+ gem 'gspec', '~> 0.1.3', group: :development
9
+ gem "pry", "~> 0.13.1", group: :development
10
+ gem "byteman", "~> 0.1.0"
data/Gemfile.lock ADDED
@@ -0,0 +1,47 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ rbimg (0.1.1)
5
+ byteman (~> 0.1.0)
6
+ require_all (~> 3.0)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ byteman (0.1.0)
12
+ coderay (1.1.3)
13
+ diff-lcs (1.4.2)
14
+ gspec (0.1.3)
15
+ method_source (1.0.0)
16
+ pry (0.13.1)
17
+ coderay (~> 1.1)
18
+ method_source (~> 1.0)
19
+ rake (12.3.3)
20
+ require_all (3.0.0)
21
+ rspec (3.9.0)
22
+ rspec-core (~> 3.9.0)
23
+ rspec-expectations (~> 3.9.0)
24
+ rspec-mocks (~> 3.9.0)
25
+ rspec-core (3.9.2)
26
+ rspec-support (~> 3.9.3)
27
+ rspec-expectations (3.9.2)
28
+ diff-lcs (>= 1.2.0, < 2.0)
29
+ rspec-support (~> 3.9.0)
30
+ rspec-mocks (3.9.1)
31
+ diff-lcs (>= 1.2.0, < 2.0)
32
+ rspec-support (~> 3.9.0)
33
+ rspec-support (3.9.3)
34
+
35
+ PLATFORMS
36
+ ruby
37
+
38
+ DEPENDENCIES
39
+ byteman (~> 0.1.0)
40
+ gspec (~> 0.1.3)
41
+ pry (~> 0.13.1)
42
+ rake (~> 12.0)
43
+ rbimg!
44
+ rspec (~> 3.0)
45
+
46
+ BUNDLED WITH
47
+ 2.1.4
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 micahshute
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,137 @@
1
+ # Rbimg
2
+
3
+ Allows simple creation and reading of images (currently only PNG images).
4
+
5
+ Supports all required chunk types (IHDR, PLTE, IDAT, IEND)
6
+
7
+ Filtering is not currently supported.
8
+
9
+ This gem is primarily for simple manipulation of images using pixel data.
10
+
11
+ You can easily write images from an array of pixel data, and retrieve pixel data from a PNG image.
12
+
13
+ Examples:
14
+
15
+ Write simple 100x100 green-blue image
16
+
17
+ ```ruby
18
+ pixels = []
19
+ 100.times do
20
+ pixels << Array.new(100, [0,255,255])
21
+ end
22
+ png = Rbimg::PNG.new(pixels: pixels.flatten, type: :rgb, width: 100, height: 100)
23
+ png.write(path: './green-blue')
24
+ ```
25
+
26
+ Write simple 500x500 half blue half red rgba image
27
+
28
+ ```ruby
29
+ pixels = []
30
+ 500.times do |row|
31
+ if row >= 250
32
+ pixels << Array.new(500, [0,0,255,127])
33
+ else
34
+ pixels << Array.new(500, [255,0,0,127])
35
+ end
36
+ end
37
+ png = Rbimg::PNG.new(pixels: pixels.flatten, type: :rgba, width: 500, height: 500)
38
+ png.write(path: './blue-red-alpha')
39
+ ```
40
+
41
+ Write simple 300x500 half white half black greyscale image
42
+
43
+ ```ruby
44
+ pixels = []
45
+ 500.times do |row|
46
+ if row >= 250
47
+ pixels << Array.new(300, 255)
48
+ else
49
+ pixels << Array.new(300, 0)
50
+ end
51
+ end
52
+ png = Rbimg::PNG.new(pixels: pixels.flatten, type: :greyscale, width: 300, height: 500)
53
+ png.write(path: './greyscale')
54
+ ```
55
+
56
+ Write a greyscale-alpha version of the image above
57
+
58
+ ```ruby
59
+ pixels = []
60
+ 500.times do |row|
61
+ if row >= 250
62
+ pixels << Array.new(300, [255,175])
63
+ else
64
+ pixels << Array.new(300, [0,175])
65
+ end
66
+ end
67
+ png = Rbimg::PNG.new(pixels: pixels.flatten, type: :greyscale_alpha, width: 300, height: 500)
68
+ png.write(path: './greyscale_alpha')
69
+ ```
70
+ Write a greyscale image from the MSNT dataset:
71
+
72
+ ```ruby
73
+ img_data = File.read("./data/t10k-images-idx3-ubyte").bytes
74
+ mag_num = img_data[0...4]
75
+ num_imgs = img_data[4...8]
76
+ num_rows = img_data[8...12]
77
+ num_cols = img_data[12...16]
78
+ pixels = img_data[16...(16 + 784)]
79
+ png = Rbimg::PNG.new(pixels: pixels, type: :greyscale, width: 28, height: 28)
80
+ png.write(path: 'mnst_test')
81
+ ```
82
+
83
+ Read a PNG image and get the pixel array from a path
84
+
85
+ ```ruby
86
+ png = Rbimg::PNG.read(path: './data/smiley.png')
87
+ puts png.pixels
88
+ ```
89
+
90
+ Read a PNG image and get the pixel array from raw data
91
+
92
+ ```ruby
93
+ data = File.read('./data/smiley.png')
94
+ png = Rbimg::PNG.read(data: data)
95
+ puts png.pixels
96
+ ```
97
+
98
+
99
+
100
+ ## Installation
101
+
102
+ Add this line to your application's Gemfile:
103
+
104
+ ```ruby
105
+ gem 'rbimg'
106
+ ```
107
+
108
+ And then execute:
109
+
110
+ $ bundle install
111
+
112
+ Or install it yourself as:
113
+
114
+ $ gem install rbimg
115
+
116
+ ## Usage
117
+
118
+ TODO: Write usage instructions here
119
+
120
+ ## Development
121
+
122
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
123
+
124
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
125
+
126
+ ## Contributing
127
+
128
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/rbimg. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/rbimg/blob/master/CODE_OF_CONDUCT.md).
129
+
130
+
131
+ ## License
132
+
133
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
134
+
135
+ ## Code of Conduct
136
+
137
+ Everyone interacting in the Rbimg project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/rbimg/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,15 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+ spec = Gem::Specification.find_by_name 'gspec'
4
+ load "#{spec.gem_dir}/lib/gspec/tasks/generator.rake"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task :default => :spec
9
+
10
+ desc "Open interactive console for this project"
11
+ task :console do
12
+ require 'pry'
13
+ require_relative './lib/rbimg'
14
+ Pry.start
15
+ end
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "rbimg"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,3 @@
1
+ class Rbimg::CRCError < StandardError
2
+
3
+ end
@@ -0,0 +1,3 @@
1
+ class Rbimg::FormatError < StandardError
2
+
3
+ end
@@ -0,0 +1,320 @@
1
+ class Rbimg::PNG
2
+
3
+
4
+ REQUIRED_CHUNKS = [
5
+ :IHDR,
6
+ :IDAT,
7
+ :IEND
8
+ ]
9
+
10
+ COLOR_TYPES = {
11
+ greyscale: 0,
12
+ rgb: 2,
13
+ pallet: 3,
14
+ greyscale_alpha: 4,
15
+ rgba: 6
16
+ }
17
+
18
+ def self.read(path: nil, data: nil)
19
+
20
+ raise ArgumentError.new(".read must be initialized with a path or a datastream") if (path.nil? && data.nil?) || (!path.nil? && !data.nil?)
21
+ raise ArgumentError.new("data must be an array of byte integers or a byte string") if data && !data.is_a?(Array) && !data.is_a?(String)
22
+ raise ArgumentError.new("data must be an array of byte integers or a byte string") if data && data.is_a?(Array) && !data.first.is_a?(Integer)
23
+ begin
24
+ if path
25
+ data = File.read(path).bytes
26
+ else
27
+ data = data.bytes if data.is_a?(String)
28
+ end
29
+ chunk_start = 8
30
+ chunks = []
31
+ loop do
32
+ len_end = chunk_start + 4
33
+ type_end = len_end + 4
34
+ len = Byteman.buf2int(data[chunk_start...len_end])
35
+ type = data[len_end...type_end]
36
+ chunk_end = type_end + len + 4
37
+ case type.pack("C*")
38
+ when "IHDR"
39
+ chunks << Chunk.readIHDR(data[chunk_start...chunk_end])
40
+ when "IDAT"
41
+ chunks << Chunk.readIDAT(data[chunk_start...chunk_end])
42
+ when "PLTE"
43
+ chunks << Chunk.readPLTE(data[chunk_start...chunk_end])
44
+ else
45
+ chunks << data[chunk_start...chunk_end]
46
+ end
47
+
48
+ chunk_start = chunk_end
49
+ break if chunk_end >= data.length - 1
50
+
51
+ end
52
+
53
+ width = chunks.first[:width]
54
+ height = chunks.first[:height]
55
+ bit_depth = chunks.first[:bit_depth]
56
+ color_type = chunks.first[:color_type]
57
+ compression_method = chunks.first[:compression_method]
58
+ filter_method = chunks.first[:filter_method]
59
+ interlace_method = chunks.first[:interlace_method]
60
+ all_idats = chunks.filter{ |c| c.is_a?(Hash) && c[:type] == "IDAT" }
61
+ compressed_pixels = all_idats.reduce([]){ |mem, idat| mem + idat[:compressed_pixels] }
62
+ pixels_and_filter = Zlib::Inflate.inflate(compressed_pixels.pack("C*")).unpack("C*")
63
+
64
+ case color_type
65
+ when 0
66
+ pixel_width = width
67
+ when 2
68
+ pixel_width = width * 3
69
+ when 3
70
+ pixel_width = width
71
+ when 4
72
+ pixel_width = width * 2
73
+ when 6
74
+ pixel_width = width * 4
75
+ else
76
+ raise ArgumentError.new("#{color_type} is not a valid color type. Must be 0,2,3,4, or 6")
77
+ end
78
+ pixels = pixels_and_filter.filter.with_index{ |_,i| i % (pixel_width + 1) != 0}
79
+ args = {pixels: pixels, type: color_type, width: width, height: height, bit_depth: bit_depth}
80
+ plte = chunks.find{|c| c[:type] == "PLTE" unless c.is_a?(Array)}
81
+ args[:palette] = plte[:chunk_data] if plte
82
+ new(**args)
83
+ rescue
84
+ raise Rbimg::FormatError.new("This PNG file is not in the correct format or has been corrupted")
85
+ end
86
+ end
87
+
88
+
89
+ attr_reader :pixels, :width, :height, :bit_depth, :compression_method, :filter_method, :interlace_method
90
+
91
+ def initialize(pixels: nil, type: nil, width: , height: , bit_depth: 8, compression_method: 0, filter_method: 0, interlace_method: 0, palette: nil)
92
+ @pixels, @width, @height, @compression_method, @filter_method, @interlace_method = pixels, width, height, compression_method, filter_method, interlace_method
93
+ @bit_depth = bit_depth
94
+ @type = type.is_a?(Integer) ? type : COLOR_TYPES[type]
95
+ raise ArgumentError.new("#{type} is not a valid color type. Please use one of: #{COLOR_TYPES.keys}") if type.nil?
96
+ raise ArgumentError.new("Palettes are not compatible with color types 0 and 4") if palette && (@type == 0 || @type == 4)
97
+ raise ArgumentError.new("palette must be an array") if palette && !palette.is_a?(Array)
98
+ @signature = [137, 80, 78, 71, 13, 10, 26, 10]
99
+ @chunks = [
100
+ Chunk.IHDR(
101
+ width: @width,
102
+ height: @height,
103
+ bit_depth: @bit_depth,
104
+ color_type: @type,
105
+ compression_method: @compression_method,
106
+ filter_method: @filter_method,
107
+ interlace_method: interlace_method
108
+ ),
109
+ *Chunk.IDATs(
110
+ pixels,
111
+ color_type: @type,
112
+ bit_depth: @bit_depth,
113
+ width: @width,
114
+ height: @height
115
+ ),
116
+ Chunk.IEND
117
+ ]
118
+ @chunks.insert(1, Chunk.PLTE(palette)) if !palette.nil?
119
+
120
+ end
121
+
122
+ def type
123
+ COLOR_TYPES.each do |k,v|
124
+ return k if v == @type
125
+ end
126
+ end
127
+
128
+ def bytes
129
+ all_data.pack("C*")
130
+ end
131
+
132
+ def write(path: Dir.pwd + "/output.png")
133
+ postscript = path.split(".").last == "png" ? "" : ".png"
134
+ File.write(path + postscript, bytes)
135
+ end
136
+
137
+ private
138
+
139
+ def all_data
140
+ @signature + @chunks.map(&:data).flatten
141
+ end
142
+
143
+ class Chunk
144
+
145
+ def self.readChunk(bytes)
146
+ bytes = bytes.bytes if bytes.is_a?(String)
147
+ data = {}
148
+ data[:length] = Byteman.buf2int(bytes[0...4])
149
+ data[:type] = Byteman.buf2hex(bytes[4...8])
150
+ data[:crc] = bytes[-4..-1]
151
+ data[:chunk_data] = bytes[8...(8 + data[:length])]
152
+ raise Rbimg::CRCError.new("CRC does not match expected") if !crc_valid?(type: data[:type].unpack("C*"), data: data[:chunk_data], crc: data[:crc])
153
+ data
154
+ end
155
+
156
+ def self.readIHDR(bytes)
157
+ bytes = bytes.bytes if bytes.is_a?(String)
158
+ raise ArgumentError.new("IHDR must be 25 bytes long") if bytes.length != 25
159
+
160
+ data = readChunk(bytes)
161
+ data[:width] = Byteman.buf2int(bytes[8...12])
162
+ data[:height] = Byteman.buf2int(bytes[12...16])
163
+ data[:bit_depth] = bytes[16]
164
+ data[:color_type] = bytes[17]
165
+ data[:compression_method] = bytes[18]
166
+ data[:filter_method] = bytes[19]
167
+ data[:interlace_method] = bytes[20]
168
+ data
169
+ end
170
+
171
+ def self.readIDAT(bytes)
172
+ data = readChunk(bytes)
173
+ data[:compressed_pixels] = data[:chunk_data]
174
+ data
175
+ end
176
+
177
+ def self.readPLTE(bytes)
178
+ readChunk(bytes)
179
+ end
180
+
181
+ def self.crc_valid?(type:, data:, crc:)
182
+ c = new(type: type, data: data)
183
+ c.bytes[-4..-1].bytes == crc
184
+ end
185
+
186
+ def self.IHDR(width: , height: , bit_depth: , color_type: , compression_method: 0, filter_method: 0, interlace_method: 0)
187
+ bit_depth_rules = {
188
+ 0 => [1,2,4,8,16],
189
+ 2 => [8, 16],
190
+ 3 => [1,2,4,8],
191
+ 4 => [8,16],
192
+ 6 => [8,16]
193
+ }
194
+
195
+ raise ArgumentError.new("Width or height cannot be 0") if width == 0 || height == 0
196
+ test_length(width)
197
+ test_length(height)
198
+ raise ArgumentError.new('Color code types must be 0, 2, 3, 4, or 6') if ![0,2,3,4,6].include?(color_type)
199
+ raise ArgumentError.new('Bit depth must be related to color_type as such: #{bit_depth_rules}') if !bit_depth_rules[color_type].include?(bit_depth)
200
+
201
+
202
+ wbytes = Byteman.pad(len: 4, num: Byteman.int2buf(width))
203
+ hbytes = Byteman.pad(len: 4, num: Byteman.int2buf(height))
204
+ bdbyte = [bit_depth]
205
+ ctbyte = [color_type]
206
+ cmbyte = [compression_method]
207
+ fmbyte = [filter_method]
208
+ ilmbyte = [interlace_method]
209
+ data = wbytes + hbytes + bdbyte + ctbyte + cmbyte + fmbyte + ilmbyte
210
+ Chunk.new(type: "IHDR", data: data)
211
+ end
212
+
213
+ def self.PLTE(data)
214
+ data = data.bytes if data.is_a?(String)
215
+ raise ArgumentError.new("Number of bytes must be a multiple of 3") if data.length % 3 != 0
216
+ raise ArgumentError.new("Pallette length must be between 1 and 256") if data.length < 3 || data.length > (256 * 3)
217
+ Chunk.new(type: "PLTE", data: data)
218
+ end
219
+
220
+ def self.IDATs(pixels, color_type: ,bit_depth:, width: , height: , idat_size: 2 ** 20)
221
+
222
+ case color_type
223
+ when 0
224
+ pixel_width = width
225
+ when 2
226
+ pixel_width = width * 3
227
+ when 3
228
+ pixel_width = width
229
+ when 4
230
+ pixel_width = width * 2
231
+ when 6
232
+ pixel_width = width * 4
233
+ else
234
+ raise ArgumentError.new("#{color_type} is not a valid color type. Must be 0,2,3,4, or 6")
235
+ end
236
+ expected_pixels = pixel_width * height
237
+ raise ArgumentError.new("pixel count (#{pixels.length}) does not match expected pixel count (#{expected_pixels})") if pixels.length != expected_pixels
238
+ pixel_square = Array.new(height, nil)
239
+ pixel_square = pixel_square.map{ |_| [nil] * pixel_width}
240
+ for i in 0...pixels.length
241
+ row = i / pixel_width
242
+ col = i % pixel_width
243
+ pixel_square[row][col] = pixels[i]
244
+ end
245
+
246
+ scanlines = pixel_square.map do |bit_strm|
247
+
248
+ case bit_depth
249
+ when 1
250
+ [0] + Byteman.hex(bit_strm.map{|b| b.to_s(2)}.join('').to_i(2))
251
+ when 2
252
+ [0] + Byteman.hex(bit_strm.map{|b| Byteman.pad(num: b.to_s(2), len: 2)}.join('').to_i(2))
253
+ when 4
254
+ [0] + Byteman.hex(bit_strm.map{|b| Byteman.pad(num: b.to_s(2), len: 4)}.join('').to_i(2))
255
+ when 8
256
+ ([0] + bit_strm).pack("C*")
257
+ when 16
258
+ ([0] + bit_strm).pack("S*")
259
+ else
260
+ ArgumentError.new("bit_depth can only be 1,2,4,8, or 16 bits")
261
+ end
262
+
263
+ end
264
+
265
+ z = Zlib::Deflate.new(Zlib::BEST_COMPRESSION, Zlib::MAX_WBITS, Zlib::MAX_MEM_LEVEL, Zlib::RLE)
266
+ zstrm = z.deflate(scanlines.join(''), Zlib::FINISH)
267
+ z.close
268
+ idats = []
269
+ zstrm.bytes.each_slice(idat_size) do |dstrm|
270
+ idats << Chunk.new(type: "IDAT", data: dstrm)
271
+ end
272
+
273
+ idats
274
+ end
275
+
276
+ def self.IEND
277
+ Chunk.new(type: "IEND", data: nil)
278
+ end
279
+
280
+
281
+ attr_reader :length, :type, :data
282
+
283
+ def initialize(type: ,data:)
284
+ raise ArgumentError.new("Type must be a string, symbol, or an array") if !type.is_a?(String) && !type.is_a?(Symbol) && !type.is_a?(Array)
285
+ @data = data.nil? ? [] : data
286
+ @length = Byteman.pad(len: 4, num: Byteman.int2buf(@data.length))
287
+ self.class.test_length(@data.length)
288
+
289
+ if type.is_a?(String) || type.is_a?(Symbol)
290
+ @type = type.to_s.bytes
291
+ else
292
+ @type = type
293
+ end
294
+ @crc_strategy = Rbimg::Strategies::CRCTableLookup
295
+ @crc = crc
296
+ end
297
+
298
+ def data
299
+ @length + @type + @data + @crc
300
+ end
301
+
302
+ def bytes
303
+ data.pack("C*")
304
+ end
305
+
306
+ private
307
+
308
+
309
+ def self.test_length(num, limit: 2 ** 31 - 1)
310
+ raise ArgumentError.new("Length cannot exceed 2^31 - 1") if num > limit
311
+ end
312
+
313
+
314
+ def crc
315
+ @crc_strategy.crc(@type, @data)
316
+ end
317
+
318
+ end
319
+
320
+ end
@@ -0,0 +1,3 @@
1
+ module Rbimg
2
+ VERSION = "0.1.1"
3
+ end
data/lib/rbimg.rb ADDED
@@ -0,0 +1,14 @@
1
+ require_relative "./rbimg/version"
2
+ require 'byteman'
3
+ require 'zlib'
4
+
5
+ module Rbimg
6
+ class Error < StandardError; end
7
+ # Your code goes here...
8
+ end
9
+
10
+ require_relative './errors/crc_error'
11
+ require_relative './errors/format_error'
12
+ require_relative './strategies/strategies'
13
+ require_relative './strategies/crc_strategies/crc_table_lookup_strategy'
14
+ require_relative './image_types/png'
@@ -0,0 +1,35 @@
1
+ class Rbimg::Strategies::CRCTableLookup
2
+
3
+ @@crc_table = {}
4
+
5
+ def self.make_crc_table
6
+ for n in 0...256
7
+ c = n
8
+ for k in 0...8
9
+ if c.odd?
10
+ c = 3988292384 ^ (c >> 1)
11
+ else
12
+ c = c >> 1
13
+ end
14
+ end
15
+ @@crc_table[n] = c
16
+ end
17
+ end
18
+
19
+ def self.crc_table_computed
20
+ @@crc_table.length > 0
21
+ end
22
+
23
+
24
+
25
+ def self.crc(type, data)
26
+ c = ([255] * 4).pack("C4").unpack("L").first
27
+ buff = type + data
28
+ make_crc_table if !crc_table_computed
29
+ for n in 0...buff.length
30
+ c = @@crc_table[(c ^ buff[n]) & 255] ^ (c >> 8)
31
+ end
32
+ Byteman.int2buf(c ^ Byteman.buf2int([255] * 4))
33
+ end
34
+
35
+ end
@@ -0,0 +1,3 @@
1
+ class Rbimg::Strategies
2
+
3
+ end
data/rbimg.gemspec ADDED
@@ -0,0 +1,31 @@
1
+ require_relative 'lib/rbimg/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "rbimg"
5
+ spec.version = Rbimg::VERSION
6
+ spec.authors = ["micahshute"]
7
+ spec.email = ["micah.shute@gmail.com"]
8
+
9
+ spec.summary = %q{Create, read, and manipulate images via arrays of pixel data}
10
+ spec.description = %q{This gem allows you to read and/or create a valid picture by working with an array of pixel data. This can be used to easily visualize the MSNT dataset, ecrypt/decrypt images, create graphs and charts, etc.}
11
+ spec.homepage = "https://github.com"
12
+ spec.license = "MIT"
13
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
14
+
15
+ # spec.metadata["allowed_push_host"] = "http://rubygems.com"
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+ spec.metadata["source_code_uri"] = "https://github.com"
19
+ spec.metadata["changelog_uri"] = "https://github.com"
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
23
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
24
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
25
+ end
26
+ spec.bindir = "exe"
27
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ["lib"]
29
+ spec.add_dependency 'byteman', "~> 0.1.0"
30
+ spec.add_dependency 'require_all', "~> 3.0"
31
+ end
metadata ADDED
@@ -0,0 +1,95 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rbimg
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - micahshute
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-07-01 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: byteman
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.1.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.1.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: require_all
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '3.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '3.0'
41
+ description: This gem allows you to read and/or create a valid picture by working
42
+ with an array of pixel data. This can be used to easily visualize the MSNT dataset,
43
+ ecrypt/decrypt images, create graphs and charts, etc.
44
+ email:
45
+ - micah.shute@gmail.com
46
+ executables: []
47
+ extensions: []
48
+ extra_rdoc_files: []
49
+ files:
50
+ - ".gitignore"
51
+ - ".rspec"
52
+ - ".travis.yml"
53
+ - CODE_OF_CONDUCT.md
54
+ - Gemfile
55
+ - Gemfile.lock
56
+ - LICENSE.txt
57
+ - README.md
58
+ - Rakefile
59
+ - bin/console
60
+ - bin/setup
61
+ - lib/errors/crc_error.rb
62
+ - lib/errors/format_error.rb
63
+ - lib/image_types/png.rb
64
+ - lib/rbimg.rb
65
+ - lib/rbimg/version.rb
66
+ - lib/strategies/crc_strategies/crc_table_lookup_strategy.rb
67
+ - lib/strategies/strategies.rb
68
+ - rbimg.gemspec
69
+ homepage: https://github.com
70
+ licenses:
71
+ - MIT
72
+ metadata:
73
+ homepage_uri: https://github.com
74
+ source_code_uri: https://github.com
75
+ changelog_uri: https://github.com
76
+ post_install_message:
77
+ rdoc_options: []
78
+ require_paths:
79
+ - lib
80
+ required_ruby_version: !ruby/object:Gem::Requirement
81
+ requirements:
82
+ - - ">="
83
+ - !ruby/object:Gem::Version
84
+ version: 2.3.0
85
+ required_rubygems_version: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ requirements: []
91
+ rubygems_version: 3.1.2
92
+ signing_key:
93
+ specification_version: 4
94
+ summary: Create, read, and manipulate images via arrays of pixel data
95
+ test_files: []