Visual Computing Library
Loading...
Searching...
No Matches
image.h
1/*****************************************************************************
2 * VCLib *
3 * Visual Computing Library *
4 * *
5 * Copyright(C) 2021-2025 *
6 * Visual Computing Lab *
7 * ISTI - Italian National Research Council *
8 * *
9 * All rights reserved. *
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the Mozilla Public License Version 2.0 as published *
13 * by the Mozilla Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 * This program is distributed in the hope that it will be useful, *
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
19 * Mozilla Public License Version 2.0 *
20 * (https://www.mozilla.org/en-US/MPL/2.0/) for more details. *
21 ****************************************************************************/
22
23#ifndef VCL_IO_IMAGE_H
24#define VCL_IO_IMAGE_H
25
26#include <vclib/io/file_info.h>
27#include <vclib/misc/string.h>
28
29#if __has_include(<stb/stb_image.h>)
30#include <stb/stb_image.h>
31#include <stb/stb_image_write.h>
32#else
33// inclusion for usage of vclib without CMake - not ideal but necessary for
34// header-only
35#define STB_IMAGE_STATIC // make stb static
36#define STB_IMAGE_IMPLEMENTATION // and then include the implementation
37#include "../../../external/stb-master/stb/stb_image.h"
38#define STB_IMAGE_WRITE_STATIC // make stb static
39#define STB_IMAGE_WRITE_IMPLEMENTATION // and then include the implementation
40#include "../../../external/stb-master/stb/stb_image_write.h"
41#endif
42
43#include <memory>
44#include <string>
45
46namespace vcl {
47
48inline std::shared_ptr<unsigned char> loadImageData(
49 const std::string& filename,
50 int& w,
51 int& h)
52{
53 std::shared_ptr<unsigned char> ptr(
54 stbi_load(filename.c_str(), &w, &h, nullptr, 4), stbi_image_free);
55 return ptr;
56}
57
58inline void saveImageData(
59 const std::string& filename,
60 int w,
61 int h,
62 const unsigned char* data,
63 uint quality = 90)
64{
65 std::string ext = FileInfo::extension(filename);
66 ext = toLower(ext);
67 int ret = 0;
68 if (ext == ".png") {
69 ret = stbi_write_png(filename.c_str(), w, h, 4, data, 0);
70 }
71 else if (ext == ".bmp") {
72 ret = stbi_write_bmp(filename.c_str(), w, h, 4, data);
73 }
74 else if (ext == ".tga") {
75 ret = stbi_write_tga(filename.c_str(), w, h, 4, data);
76 }
77 else if (ext == ".jpg" || ext == ".jpeg") {
78 ret = stbi_write_jpg(filename.c_str(), w, h, 4, data, quality);
79 }
80 else {
81 throw UnknownFileFormatException(ext);
82 }
83
84 if (ret == 0) {
85 throw CannotOpenFileException(filename);
86 }
87}
88
89} // namespace vcl
90
91#endif // VCL_IO_IMAGE_H
static std::string extension(const std::string &filename)
Get the extension of a file.
Definition file_info.h:257