1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
/*
* Processing of images uploaded by the user
* (resizing, cropping, saving)
*/
#include "img_handler.hpp"
#include "puzzle.hpp"
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#include "lib/stb_image.h"
#include "lib/stb_image_resize2.h"
#include "lib/stb_image_write.h"
#include <stdlib.h>
#include <filesystem>
#include <stdio.h>
#include <iostream>
#include <string>
ImageHandler::ImageHandler(const char *p) : source_path(p) {
img_data = nullptr;
resized_data = nullptr;
/*
* creating resources directory (if it didn't exist)
*/
std::filesystem::path res_path = std::string("resources");
if(!std::filesystem::exists(res_path))
std::filesystem::create_directory(res_path);
#if defined(_WIN32)
auto it = source_path.find_last_of('\\');
#else
auto it = source_path.find_last_of('/');
#endif
std::string file_name = source_path.substr(it + 1);
std::string fn_withot_ext =
file_name.substr(0, file_name.find_first_of('.'));
#if defined(_WIN32)
destination_directory = "resources\\" + fn_withot_ext + "\\";
#else
destination_directory = "resources/" + fn_withot_ext + '/';
#endif
std::filesystem::create_directory(destination_directory);
}
void ImageHandler::load_img()
{
img_data = stbi_load(source_path.c_str(), &in_width, &in_height,
&channel, 0);
}
void ImageHandler::resize_img()
{
resized_data =
reinterpret_cast<unsigned char*>(malloc(in_width * in_height *
channel));
stbir_resize_uint8_linear(img_data, in_width, in_height, 0, resized_data,
width, height, 0, (stbir_pixel_layout) channel);
}
void ImageHandler::save_img()
{
int x, y, i, j, k = 0;
for(i = 0; i < puzzles_per_side; ++i)
for(j = 0; j < puzzles_per_side; ++j, ++k) {
x = i * puzzle_size;
y = j * puzzle_size;
std::string tmp_path =
destination_directory +
std::to_string(k / puzzles_per_side) +
std::to_string(k % puzzles_per_side) + ".png";
stbi_write_png(tmp_path.c_str(), puzzle_size, puzzle_size, channel,
resized_data + channel * (x + y * width),
width * channel);
}
stbi_image_free(resized_data);
stbi_image_free(img_data);
}
|