Visual Computing Library  devel
Loading...
Searching...
No Matches
save.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_STB_SAVE_H
24#define VCL_IO_IMAGE_STB_SAVE_H
25
26#include <vclib/io/exceptions.h>
27#include <vclib/io/file_info.h>
28
29// disable deprecated warnings - just for stb
30#if defined(__clang__)
31#pragma clang diagnostic push
32#pragma clang diagnostic ignored "-Wdeprecated-declarations"
33#endif
34
35#include <stb_image_write.h>
36
37#if defined(__clang__)
38#pragma clang diagnostic pop
39#endif
40
41#include <set>
42#include <string>
43
44namespace vcl::stb {
45
46inline std::set<FileFormat> saveImageFormats()
47{
48 return {
49 FileFormat("png", "Portable Network Graphics"),
50 FileFormat("bmp", "Bitmap"),
51 FileFormat("tga", "Truevision TGA"),
52 FileFormat(
53 std::vector<std::string> {"jpg", "jpeg"},
54 "Joint Photographic Experts Group"),
55 };
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::stb
90
91#endif // VCL_IO_IMAGE_STB_SAVE_H
static std::string extension(const std::string &filename)
Get the extension of a file.
Definition file_info.h:260