fast_resize 1.0.0

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.
Files changed (55) hide show
  1. checksums.yaml +7 -0
  2. data/CMakeLists.txt +308 -0
  3. data/LICENSE +29 -0
  4. data/README.md +426 -0
  5. data/VERSION +1 -0
  6. data/bindings/ruby/ext/fastresize/extconf.rb +152 -0
  7. data/bindings/ruby/ext/fastresize/fastresize_ext.cpp +377 -0
  8. data/bindings/ruby/lib/fastresize/platform.rb +106 -0
  9. data/bindings/ruby/lib/fastresize/version.rb +5 -0
  10. data/bindings/ruby/lib/fastresize.rb +13 -0
  11. data/bindings/ruby/prebuilt/linux-aarch64/bin/fast_resize +0 -0
  12. data/bindings/ruby/prebuilt/linux-aarch64/include/fastresize.h +189 -0
  13. data/bindings/ruby/prebuilt/linux-aarch64/include/stb_image.h +7988 -0
  14. data/bindings/ruby/prebuilt/linux-aarch64/include/stb_image_resize2.h +10651 -0
  15. data/bindings/ruby/prebuilt/linux-aarch64/include/stb_image_write.h +1724 -0
  16. data/bindings/ruby/prebuilt/linux-aarch64/lib/libfastresize.a +0 -0
  17. data/bindings/ruby/prebuilt/linux-aarch64.tar.gz +0 -0
  18. data/bindings/ruby/prebuilt/linux-x86_64/bin/fast_resize +0 -0
  19. data/bindings/ruby/prebuilt/linux-x86_64/include/fastresize.h +189 -0
  20. data/bindings/ruby/prebuilt/linux-x86_64/include/stb_image.h +7988 -0
  21. data/bindings/ruby/prebuilt/linux-x86_64/include/stb_image_resize2.h +10651 -0
  22. data/bindings/ruby/prebuilt/linux-x86_64/include/stb_image_write.h +1724 -0
  23. data/bindings/ruby/prebuilt/linux-x86_64/lib/libfastresize.a +0 -0
  24. data/bindings/ruby/prebuilt/linux-x86_64.tar.gz +0 -0
  25. data/bindings/ruby/prebuilt/macos-arm64/bin/fast_resize +0 -0
  26. data/bindings/ruby/prebuilt/macos-arm64/include/fastresize.h +189 -0
  27. data/bindings/ruby/prebuilt/macos-arm64/include/stb_image.h +7988 -0
  28. data/bindings/ruby/prebuilt/macos-arm64/include/stb_image_resize2.h +10651 -0
  29. data/bindings/ruby/prebuilt/macos-arm64/include/stb_image_write.h +1724 -0
  30. data/bindings/ruby/prebuilt/macos-arm64/lib/libfastresize.a +0 -0
  31. data/bindings/ruby/prebuilt/macos-arm64.tar.gz +0 -0
  32. data/bindings/ruby/prebuilt/macos-x86_64/bin/fast_resize +0 -0
  33. data/bindings/ruby/prebuilt/macos-x86_64/include/fastresize.h +189 -0
  34. data/bindings/ruby/prebuilt/macos-x86_64/include/stb_image.h +7988 -0
  35. data/bindings/ruby/prebuilt/macos-x86_64/include/stb_image_resize2.h +10651 -0
  36. data/bindings/ruby/prebuilt/macos-x86_64/include/stb_image_write.h +1724 -0
  37. data/bindings/ruby/prebuilt/macos-x86_64/lib/libfastresize.a +0 -0
  38. data/bindings/ruby/prebuilt/macos-x86_64.tar.gz +0 -0
  39. data/include/fastresize.h +189 -0
  40. data/include/stb_image.h +7988 -0
  41. data/include/stb_image_resize2.h +10651 -0
  42. data/include/stb_image_write.h +1724 -0
  43. data/src/cli.cpp +540 -0
  44. data/src/decoder.cpp +647 -0
  45. data/src/encoder.cpp +376 -0
  46. data/src/fastresize.cpp +445 -0
  47. data/src/internal.h +108 -0
  48. data/src/pipeline.cpp +284 -0
  49. data/src/pipeline.h +175 -0
  50. data/src/resizer.cpp +199 -0
  51. data/src/simd_resize.cpp +384 -0
  52. data/src/simd_resize.h +72 -0
  53. data/src/simd_utils.h +127 -0
  54. data/src/thread_pool.cpp +232 -0
  55. metadata +158 -0
@@ -0,0 +1,377 @@
1
+ /*
2
+ * FastResize - The Fastest Image Resizing Library On The Planet
3
+ * Copyright (C) 2025 Tran Huu Canh (0xTh3OKrypt) and FastResize Contributors
4
+ *
5
+ * Resize 1,000 images in 2 seconds. Up to 2.9x faster than libvips,
6
+ * 3.1x faster than imageflow. Uses 3-4x less RAM than alternatives.
7
+ *
8
+ * Author: Tran Huu Canh (0xTh3OKrypt)
9
+ * Email: tranhuucanh39@gmail.com
10
+ * Homepage: https://github.com/tranhuucanh/fast_resize
11
+ *
12
+ * BSD 3-Clause License
13
+ *
14
+ * Redistribution and use in source and binary forms, with or without
15
+ * modification, are permitted provided that the following conditions are met:
16
+ *
17
+ * 1. Redistributions of source code must retain the above copyright notice,
18
+ * this list of conditions and the following disclaimer.
19
+ *
20
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
21
+ * this list of conditions and the following disclaimer in the documentation
22
+ * and/or other materials provided with the distribution.
23
+ *
24
+ * 3. Neither the name of the copyright holder nor the names of its
25
+ * contributors may be used to endorse or promote products derived from
26
+ * this software without specific prior written permission.
27
+ *
28
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
29
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
32
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
36
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
38
+ * THE POSSIBILITY OF SUCH DAMAGE.
39
+ */
40
+
41
+ #include <ruby.h>
42
+ #include <ruby/thread.h>
43
+ #include <fastresize.h>
44
+ #include <string>
45
+ #include <vector>
46
+
47
+ static VALUE rb_mFastResize;
48
+
49
+ static std::string rb_string_to_cpp(VALUE rb_str) {
50
+ Check_Type(rb_str, T_STRING);
51
+ return std::string(RSTRING_PTR(rb_str), RSTRING_LEN(rb_str));
52
+ }
53
+
54
+ static fastresize::ResizeOptions parse_resize_options(VALUE options) {
55
+ fastresize::ResizeOptions opts;
56
+
57
+ if (NIL_P(options)) {
58
+ return opts;
59
+ }
60
+
61
+ Check_Type(options, T_HASH);
62
+
63
+ VALUE width = rb_hash_aref(options, ID2SYM(rb_intern("width")));
64
+ if (!NIL_P(width)) {
65
+ opts.target_width = NUM2INT(width);
66
+ }
67
+
68
+ VALUE height = rb_hash_aref(options, ID2SYM(rb_intern("height")));
69
+ if (!NIL_P(height)) {
70
+ opts.target_height = NUM2INT(height);
71
+ }
72
+
73
+ VALUE scale = rb_hash_aref(options, ID2SYM(rb_intern("scale")));
74
+ if (!NIL_P(scale)) {
75
+ opts.scale_percent = (float)NUM2DBL(scale) / 100.0f;
76
+ if (opts.scale_percent <= 0) {
77
+ rb_raise(rb_eArgError, "Scale must be positive");
78
+ }
79
+ opts.mode = fastresize::ResizeOptions::SCALE_PERCENT;
80
+ } else if (!NIL_P(width) && !NIL_P(height)) {
81
+ opts.mode = fastresize::ResizeOptions::EXACT_SIZE;
82
+ } else if (!NIL_P(width)) {
83
+ opts.mode = fastresize::ResizeOptions::FIT_WIDTH;
84
+ } else if (!NIL_P(height)) {
85
+ opts.mode = fastresize::ResizeOptions::FIT_HEIGHT;
86
+ }
87
+
88
+ VALUE quality = rb_hash_aref(options, ID2SYM(rb_intern("quality")));
89
+ if (!NIL_P(quality)) {
90
+ opts.quality = NUM2INT(quality);
91
+ if (opts.quality < 1 || opts.quality > 100) {
92
+ rb_raise(rb_eArgError, "Quality must be between 1 and 100");
93
+ }
94
+ }
95
+
96
+ VALUE keep_aspect = rb_hash_aref(options, ID2SYM(rb_intern("keep_aspect_ratio")));
97
+ if (!NIL_P(keep_aspect)) {
98
+ opts.keep_aspect_ratio = RTEST(keep_aspect);
99
+ }
100
+
101
+ VALUE overwrite = rb_hash_aref(options, ID2SYM(rb_intern("overwrite")));
102
+ if (!NIL_P(overwrite)) {
103
+ opts.overwrite_input = RTEST(overwrite);
104
+ }
105
+
106
+ if (opts.target_width < 0) {
107
+ rb_raise(rb_eArgError, "Width must be non-negative");
108
+ }
109
+ if (opts.target_height < 0) {
110
+ rb_raise(rb_eArgError, "Height must be non-negative");
111
+ }
112
+
113
+ VALUE filter = rb_hash_aref(options, ID2SYM(rb_intern("filter")));
114
+ if (!NIL_P(filter)) {
115
+ Check_Type(filter, T_SYMBOL);
116
+ ID filter_id = SYM2ID(filter);
117
+
118
+ if (filter_id == rb_intern("mitchell")) {
119
+ opts.filter = fastresize::ResizeOptions::MITCHELL;
120
+ } else if (filter_id == rb_intern("catmull_rom")) {
121
+ opts.filter = fastresize::ResizeOptions::CATMULL_ROM;
122
+ } else if (filter_id == rb_intern("box")) {
123
+ opts.filter = fastresize::ResizeOptions::BOX;
124
+ } else if (filter_id == rb_intern("triangle")) {
125
+ opts.filter = fastresize::ResizeOptions::TRIANGLE;
126
+ } else {
127
+ rb_raise(rb_eArgError, "Invalid filter. Use :mitchell, :catmull_rom, :box, or :triangle");
128
+ }
129
+ }
130
+
131
+ return opts;
132
+ }
133
+
134
+ struct ResizeParams {
135
+ std::string input;
136
+ std::string output;
137
+ fastresize::ResizeOptions opts;
138
+ bool success;
139
+ std::string error;
140
+ };
141
+
142
+ static void* resize_without_gvl(void* data) {
143
+ ResizeParams* params = static_cast<ResizeParams*>(data);
144
+ try {
145
+ params->success = fastresize::resize(params->input, params->output, params->opts);
146
+ if (!params->success) {
147
+ params->error = fastresize::get_last_error();
148
+ }
149
+ } catch (const std::exception& e) {
150
+ params->success = false;
151
+ params->error = std::string("Exception: ") + e.what();
152
+ }
153
+ return nullptr;
154
+ }
155
+
156
+ static VALUE rb_fastresize_resize(int argc, VALUE* argv, VALUE self) {
157
+ VALUE input_path, output_path, options;
158
+ rb_scan_args(argc, argv, "21", &input_path, &output_path, &options);
159
+
160
+ try {
161
+ ResizeParams params;
162
+ params.input = rb_string_to_cpp(input_path);
163
+ params.output = rb_string_to_cpp(output_path);
164
+ params.opts = parse_resize_options(options);
165
+
166
+ rb_thread_call_without_gvl(resize_without_gvl, &params, RUBY_UBF_IO, nullptr);
167
+
168
+ if (!params.success) {
169
+ rb_raise(rb_eRuntimeError, "Resize failed: %s", params.error.c_str());
170
+ }
171
+
172
+ return Qtrue;
173
+ } catch (const std::exception& e) {
174
+ rb_raise(rb_eRuntimeError, "Resize failed: %s", e.what());
175
+ }
176
+ }
177
+
178
+ struct ResizeWithFormatParams {
179
+ std::string input;
180
+ std::string output;
181
+ std::string format;
182
+ fastresize::ResizeOptions opts;
183
+ bool success;
184
+ std::string error;
185
+ };
186
+
187
+ static void* resize_with_format_without_gvl(void* data) {
188
+ ResizeWithFormatParams* params = static_cast<ResizeWithFormatParams*>(data);
189
+ try {
190
+ params->success = fastresize::resize_with_format(params->input, params->output, params->format, params->opts);
191
+ if (!params->success) {
192
+ params->error = fastresize::get_last_error();
193
+ }
194
+ } catch (const std::exception& e) {
195
+ params->success = false;
196
+ params->error = std::string("Exception: ") + e.what();
197
+ }
198
+ return nullptr;
199
+ }
200
+
201
+ static VALUE rb_fastresize_resize_with_format(int argc, VALUE* argv, VALUE self) {
202
+ VALUE input_path, output_path, format, options;
203
+ rb_scan_args(argc, argv, "31", &input_path, &output_path, &format, &options);
204
+
205
+ try {
206
+ ResizeWithFormatParams params;
207
+ params.input = rb_string_to_cpp(input_path);
208
+ params.output = rb_string_to_cpp(output_path);
209
+ params.format = rb_string_to_cpp(format);
210
+ params.opts = parse_resize_options(options);
211
+
212
+ rb_thread_call_without_gvl(resize_with_format_without_gvl, &params, RUBY_UBF_IO, nullptr);
213
+
214
+ if (!params.success) {
215
+ rb_raise(rb_eRuntimeError, "Resize with format failed: %s", params.error.c_str());
216
+ }
217
+
218
+ return Qtrue;
219
+ } catch (const std::exception& e) {
220
+ rb_raise(rb_eRuntimeError, "Resize with format failed: %s", e.what());
221
+ }
222
+ }
223
+
224
+ static VALUE rb_fastresize_image_info(VALUE self, VALUE path) {
225
+ try {
226
+ std::string path_str = rb_string_to_cpp(path);
227
+ fastresize::ImageInfo info = fastresize::get_image_info(path_str);
228
+
229
+ VALUE result = rb_hash_new();
230
+ rb_hash_aset(result, ID2SYM(rb_intern("width")), INT2NUM(info.width));
231
+ rb_hash_aset(result, ID2SYM(rb_intern("height")), INT2NUM(info.height));
232
+ rb_hash_aset(result, ID2SYM(rb_intern("channels")), INT2NUM(info.channels));
233
+ rb_hash_aset(result, ID2SYM(rb_intern("format")), rb_str_new_cstr(info.format.c_str()));
234
+
235
+ return result;
236
+ } catch (const std::exception& e) {
237
+ rb_raise(rb_eRuntimeError, "Get image info failed: %s", e.what());
238
+ }
239
+ }
240
+
241
+ static VALUE rb_fastresize_batch_resize(int argc, VALUE* argv, VALUE self) {
242
+ VALUE input_paths, output_dir, options;
243
+ rb_scan_args(argc, argv, "21", &input_paths, &output_dir, &options);
244
+
245
+ Check_Type(input_paths, T_ARRAY);
246
+
247
+ try {
248
+ std::vector<std::string> inputs;
249
+ long len = RARRAY_LEN(input_paths);
250
+ for (long i = 0; i < len; ++i) {
251
+ VALUE item = rb_ary_entry(input_paths, i);
252
+ inputs.push_back(rb_string_to_cpp(item));
253
+ }
254
+
255
+ std::string out_dir = rb_string_to_cpp(output_dir);
256
+ fastresize::ResizeOptions resize_opts = parse_resize_options(options);
257
+
258
+ fastresize::BatchOptions batch_opts;
259
+ if (!NIL_P(options)) {
260
+ VALUE threads = rb_hash_aref(options, ID2SYM(rb_intern("threads")));
261
+ if (!NIL_P(threads)) {
262
+ batch_opts.num_threads = NUM2INT(threads);
263
+ }
264
+
265
+ VALUE stop_on_error = rb_hash_aref(options, ID2SYM(rb_intern("stop_on_error")));
266
+ if (!NIL_P(stop_on_error)) {
267
+ batch_opts.stop_on_error = RTEST(stop_on_error);
268
+ }
269
+
270
+ VALUE max_speed = rb_hash_aref(options, ID2SYM(rb_intern("max_speed")));
271
+ if (!NIL_P(max_speed)) {
272
+ batch_opts.max_speed = RTEST(max_speed);
273
+ }
274
+ }
275
+
276
+ fastresize::BatchResult result = fastresize::batch_resize(inputs, out_dir, resize_opts, batch_opts);
277
+
278
+ VALUE rb_result = rb_hash_new();
279
+ rb_hash_aset(rb_result, ID2SYM(rb_intern("total")), INT2NUM(result.total));
280
+ rb_hash_aset(rb_result, ID2SYM(rb_intern("success")), INT2NUM(result.success));
281
+ rb_hash_aset(rb_result, ID2SYM(rb_intern("failed")), INT2NUM(result.failed));
282
+
283
+ VALUE errors = rb_ary_new();
284
+ for (const auto& error : result.errors) {
285
+ rb_ary_push(errors, rb_str_new_cstr(error.c_str()));
286
+ }
287
+ rb_hash_aset(rb_result, ID2SYM(rb_intern("errors")), errors);
288
+
289
+ return rb_result;
290
+ } catch (const std::exception& e) {
291
+ rb_raise(rb_eRuntimeError, "Batch resize failed: %s", e.what());
292
+ }
293
+ }
294
+
295
+ static VALUE rb_fastresize_batch_resize_custom(int argc, VALUE* argv, VALUE self) {
296
+ VALUE items, options;
297
+ rb_scan_args(argc, argv, "11", &items, &options);
298
+
299
+ Check_Type(items, T_ARRAY);
300
+
301
+ try {
302
+ std::vector<fastresize::BatchItem> batch_items;
303
+ long len = RARRAY_LEN(items);
304
+ for (long i = 0; i < len; ++i) {
305
+ VALUE item = rb_ary_entry(items, i);
306
+ Check_Type(item, T_HASH);
307
+
308
+ fastresize::BatchItem batch_item;
309
+
310
+ VALUE input = rb_hash_aref(item, ID2SYM(rb_intern("input")));
311
+ if (NIL_P(input)) {
312
+ rb_raise(rb_eArgError, "Item %ld missing 'input' key", i);
313
+ }
314
+ batch_item.input_path = rb_string_to_cpp(input);
315
+
316
+ VALUE output = rb_hash_aref(item, ID2SYM(rb_intern("output")));
317
+ if (NIL_P(output)) {
318
+ rb_raise(rb_eArgError, "Item %ld missing 'output' key", i);
319
+ }
320
+ batch_item.output_path = rb_string_to_cpp(output);
321
+
322
+ batch_item.options = parse_resize_options(item);
323
+
324
+ batch_items.push_back(batch_item);
325
+ }
326
+
327
+ fastresize::BatchOptions batch_opts;
328
+ if (!NIL_P(options)) {
329
+ VALUE threads = rb_hash_aref(options, ID2SYM(rb_intern("threads")));
330
+ if (!NIL_P(threads)) {
331
+ batch_opts.num_threads = NUM2INT(threads);
332
+ }
333
+
334
+ VALUE stop_on_error = rb_hash_aref(options, ID2SYM(rb_intern("stop_on_error")));
335
+ if (!NIL_P(stop_on_error)) {
336
+ batch_opts.stop_on_error = RTEST(stop_on_error);
337
+ }
338
+
339
+ VALUE max_speed = rb_hash_aref(options, ID2SYM(rb_intern("max_speed")));
340
+ if (!NIL_P(max_speed)) {
341
+ batch_opts.max_speed = RTEST(max_speed);
342
+ }
343
+ }
344
+
345
+ fastresize::BatchResult result = fastresize::batch_resize_custom(batch_items, batch_opts);
346
+
347
+ VALUE rb_result = rb_hash_new();
348
+ rb_hash_aset(rb_result, ID2SYM(rb_intern("total")), INT2NUM(result.total));
349
+ rb_hash_aset(rb_result, ID2SYM(rb_intern("success")), INT2NUM(result.success));
350
+ rb_hash_aset(rb_result, ID2SYM(rb_intern("failed")), INT2NUM(result.failed));
351
+
352
+ VALUE errors = rb_ary_new();
353
+ for (const auto& error : result.errors) {
354
+ rb_ary_push(errors, rb_str_new_cstr(error.c_str()));
355
+ }
356
+ rb_hash_aset(rb_result, ID2SYM(rb_intern("errors")), errors);
357
+
358
+ return rb_result;
359
+ } catch (const std::exception& e) {
360
+ rb_raise(rb_eRuntimeError, "Batch resize custom failed: %s", e.what());
361
+ }
362
+ }
363
+
364
+ extern "C" void Init_fastresize_ext(void) {
365
+ rb_mFastResize = rb_define_module("FastResize");
366
+
367
+ rb_define_singleton_method(rb_mFastResize, "resize",
368
+ RUBY_METHOD_FUNC(rb_fastresize_resize), -1);
369
+ rb_define_singleton_method(rb_mFastResize, "resize_with_format",
370
+ RUBY_METHOD_FUNC(rb_fastresize_resize_with_format), -1);
371
+ rb_define_singleton_method(rb_mFastResize, "image_info",
372
+ RUBY_METHOD_FUNC(rb_fastresize_image_info), 1);
373
+ rb_define_singleton_method(rb_mFastResize, "batch_resize",
374
+ RUBY_METHOD_FUNC(rb_fastresize_batch_resize), -1);
375
+ rb_define_singleton_method(rb_mFastResize, "batch_resize_custom",
376
+ RUBY_METHOD_FUNC(rb_fastresize_batch_resize_custom), -1);
377
+ }
@@ -0,0 +1,106 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rbconfig'
4
+
5
+ module FastResize
6
+ # Platform detection and prebuilt binary management
7
+ module Platform
8
+ class << self
9
+ # Detect the current platform
10
+ # @return [String] Platform identifier (e.g., 'macos-arm64', 'linux-x86_64')
11
+ def detect
12
+ os = RbConfig::CONFIG['host_os']
13
+ arch = RbConfig::CONFIG['host_cpu']
14
+
15
+ platform = case os
16
+ when /darwin/
17
+ case arch
18
+ when /arm64|aarch64/ then 'macos-arm64'
19
+ when /x86_64|x64/ then 'macos-x86_64'
20
+ else
21
+ raise "Unsupported macOS architecture: #{arch}"
22
+ end
23
+ when /linux/
24
+ case arch
25
+ when /x86_64|x64/ then 'linux-x86_64'
26
+ when /arm64|aarch64/ then 'linux-aarch64'
27
+ else
28
+ raise "Unsupported Linux architecture: #{arch}"
29
+ end
30
+ else
31
+ raise "Unsupported operating system: #{os}"
32
+ end
33
+
34
+ platform
35
+ end
36
+
37
+ # Find the prebuilt library for the current platform
38
+ # @return [String] Path to the prebuilt library
39
+ # @raise [RuntimeError] if library not found
40
+ def find_library
41
+ platform = detect
42
+ base_dir = File.expand_path('../../prebuilt', __dir__)
43
+ lib_path = File.join(base_dir, platform, 'lib', 'libfastresize.a')
44
+
45
+ # Try direct path first
46
+ return lib_path if File.exist?(lib_path)
47
+
48
+ # Try extracting from tarball
49
+ tarball_path = File.join(base_dir, "#{platform}.tar.gz")
50
+ if File.exist?(tarball_path)
51
+ extract_library(tarball_path, File.join(base_dir, platform))
52
+ return lib_path if File.exist?(lib_path)
53
+ end
54
+
55
+ raise "Pre-built library not found for #{platform}. " \
56
+ "Please install from source or report this issue."
57
+ end
58
+
59
+ # Check if a prebuilt library exists for the current platform
60
+ # @return [Boolean]
61
+ def prebuilt_available?
62
+ platform = detect
63
+ base_dir = File.expand_path('../../prebuilt', __dir__)
64
+ lib_path = File.join(base_dir, platform, 'lib', 'libfastresize.a')
65
+
66
+ File.exist?(lib_path) || File.exist?(File.join(base_dir, "#{platform}.tar.gz"))
67
+ end
68
+
69
+ # Get human-readable platform information
70
+ # @return [Hash] Platform details
71
+ def info
72
+ {
73
+ platform: detect,
74
+ os: RbConfig::CONFIG['host_os'],
75
+ arch: RbConfig::CONFIG['host_cpu'],
76
+ ruby_version: RUBY_VERSION,
77
+ prebuilt_available: prebuilt_available?
78
+ }
79
+ end
80
+
81
+ private
82
+
83
+ # Extract library from tarball
84
+ # @param tarball_path [String] Path to tarball
85
+ # @param dest_dir [String] Destination directory
86
+ def extract_library(tarball_path, dest_dir)
87
+ require 'rubygems/package'
88
+ require 'zlib'
89
+
90
+ File.open(tarball_path, 'rb') do |file|
91
+ Gem::Package::TarReader.new(Zlib::GzipReader.new(file)) do |tar|
92
+ tar.each do |entry|
93
+ next unless entry.file?
94
+
95
+ dest_path = File.join(dest_dir, entry.full_name.sub(%r{^[^/]+/}, ''))
96
+ FileUtils.mkdir_p(File.dirname(dest_path))
97
+ File.open(dest_path, 'wb') do |f|
98
+ f.write(entry.read)
99
+ end
100
+ end
101
+ end
102
+ end
103
+ end
104
+ end
105
+ end
106
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FastResize
4
+ VERSION = "1.0.0"
5
+ end
@@ -0,0 +1,13 @@
1
+ require 'fastresize/fastresize_ext'
2
+
3
+ module FastResize
4
+ VERSION = File.read(File.expand_path('../../../VERSION', __dir__)).strip
5
+
6
+ class Error < StandardError; end
7
+
8
+ class << self
9
+ def version
10
+ VERSION
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,189 @@
1
+ /*
2
+ * FastResize - The Fastest Image Resizing Library On The Planet
3
+ * Copyright (C) 2025 Tran Huu Canh (0xTh3OKrypt) and FastResize Contributors
4
+ *
5
+ * Resize 1,000 images in 2 seconds. Up to 2.9x faster than libvips,
6
+ * 3.1x faster than imageflow. Uses 3-4x less RAM than alternatives.
7
+ *
8
+ * Author: Tran Huu Canh (0xTh3OKrypt)
9
+ * Email: tranhuucanh39@gmail.com
10
+ * Homepage: https://github.com/tranhuucanh/fast_resize
11
+ *
12
+ * BSD 3-Clause License
13
+ *
14
+ * Redistribution and use in source and binary forms, with or without
15
+ * modification, are permitted provided that the following conditions are met:
16
+ *
17
+ * 1. Redistributions of source code must retain the above copyright notice,
18
+ * this list of conditions and the following disclaimer.
19
+ *
20
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
21
+ * this list of conditions and the following disclaimer in the documentation
22
+ * and/or other materials provided with the distribution.
23
+ *
24
+ * 3. Neither the name of the copyright holder nor the names of its
25
+ * contributors may be used to endorse or promote products derived from
26
+ * this software without specific prior written permission.
27
+ *
28
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
29
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
32
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
36
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
38
+ * THE POSSIBILITY OF SUCH DAMAGE.
39
+ */
40
+
41
+ #ifndef FASTRESIZE_H
42
+ #define FASTRESIZE_H
43
+
44
+ #include <string>
45
+ #include <vector>
46
+
47
+ namespace fastresize {
48
+
49
+ // ============================================
50
+ // Core Structures
51
+ // ============================================
52
+
53
+ struct ResizeOptions {
54
+ // Resize mode
55
+ enum Mode {
56
+ SCALE_PERCENT, // Scale by percentage
57
+ FIT_WIDTH, // Fixed width, height auto
58
+ FIT_HEIGHT, // Fixed height, width auto
59
+ EXACT_SIZE // Exact width & height
60
+ } mode;
61
+
62
+ // Dimensions
63
+ int target_width; // Target width (pixels)
64
+ int target_height; // Target height (pixels)
65
+ float scale_percent; // Scale percentage (0.0-1.0)
66
+
67
+ // Options
68
+ bool keep_aspect_ratio; // Preserve aspect ratio (default: true)
69
+ bool overwrite_input; // Overwrite input file (default: false)
70
+
71
+ // Quality
72
+ int quality; // JPEG/WEBP quality 1-100 (default: 85)
73
+
74
+ // Filter
75
+ enum Filter {
76
+ MITCHELL, // Default, good balance
77
+ CATMULL_ROM, // Sharp edges
78
+ BOX, // Fast, lower quality
79
+ TRIANGLE // Bilinear
80
+ } filter;
81
+
82
+ // Constructor with defaults
83
+ ResizeOptions()
84
+ : mode(EXACT_SIZE)
85
+ , target_width(0)
86
+ , target_height(0)
87
+ , scale_percent(1.0f)
88
+ , keep_aspect_ratio(true)
89
+ , overwrite_input(false)
90
+ , quality(85)
91
+ , filter(MITCHELL)
92
+ {}
93
+ };
94
+
95
+ struct ImageInfo {
96
+ int width;
97
+ int height;
98
+ int channels; // 1=Gray, 3=RGB, 4=RGBA
99
+ std::string format; // "jpg", "png", "webp", "bmp"
100
+ };
101
+
102
+ // ============================================
103
+ // Single Image Resize
104
+ // ============================================
105
+
106
+ // Resize single image (auto-detect format)
107
+ bool resize(
108
+ const std::string& input_path,
109
+ const std::string& output_path,
110
+ const ResizeOptions& options
111
+ );
112
+
113
+ // Resize with explicit format
114
+ bool resize_with_format(
115
+ const std::string& input_path,
116
+ const std::string& output_path,
117
+ const std::string& output_format, // "jpg", "png", "webp", "bmp"
118
+ const ResizeOptions& options
119
+ );
120
+
121
+ // Get image info without loading
122
+ ImageInfo get_image_info(const std::string& path);
123
+
124
+ // ============================================
125
+ // Batch Processing
126
+ // ============================================
127
+
128
+ struct BatchItem {
129
+ std::string input_path;
130
+ std::string output_path;
131
+ ResizeOptions options; // Per-image options
132
+ };
133
+
134
+ struct BatchOptions {
135
+ int num_threads; // Thread pool size (0 = auto-detect, default: 0)
136
+ bool stop_on_error; // Stop if any image fails (default: false)
137
+ bool max_speed; // Enable Phase C pipeline (faster but uses more RAM, default: false)
138
+
139
+ BatchOptions()
140
+ : num_threads(0) // Phase A Optimization #7: Auto-detect thread count
141
+ , stop_on_error(false)
142
+ , max_speed(false) // Phase C: Default to balanced mode (no extra RAM)
143
+ {}
144
+ };
145
+
146
+ struct BatchResult {
147
+ int total; // Total images
148
+ int success; // Successfully processed
149
+ int failed; // Failed to process
150
+ std::vector<std::string> errors; // Error messages
151
+ };
152
+
153
+ // Batch resize - same options for all images
154
+ BatchResult batch_resize(
155
+ const std::vector<std::string>& input_paths,
156
+ const std::string& output_dir,
157
+ const ResizeOptions& options,
158
+ const BatchOptions& batch_opts = BatchOptions()
159
+ );
160
+
161
+ // Batch resize - individual options per image
162
+ BatchResult batch_resize_custom(
163
+ const std::vector<BatchItem>& items,
164
+ const BatchOptions& batch_opts = BatchOptions()
165
+ );
166
+
167
+ // ============================================
168
+ // Error Handling
169
+ // ============================================
170
+
171
+ // Get last error message
172
+ std::string get_last_error();
173
+
174
+ // Error codes
175
+ enum ErrorCode {
176
+ OK = 0,
177
+ FILE_NOT_FOUND,
178
+ UNSUPPORTED_FORMAT,
179
+ DECODE_ERROR,
180
+ RESIZE_ERROR,
181
+ ENCODE_ERROR,
182
+ WRITE_ERROR
183
+ };
184
+
185
+ ErrorCode get_last_error_code();
186
+
187
+ } // namespace fastresize
188
+
189
+ #endif // FASTRESIZE_H