Skip to content

Instantly share code, notes, and snippets.

@thomasjo
Created March 31, 2015 21:39
Show Gist options
  • Select an option

  • Save thomasjo/22a05137d99d9acfa073 to your computer and use it in GitHub Desktop.

Select an option

Save thomasjo/22a05137d99d9acfa073 to your computer and use it in GitHub Desktop.
Femto scale C++ wrapper around LibTIFF
#pragma once
#include <cstdint>
#include <vector>
namespace tiffy {
template<typename T, typename ...Targs>
std::unique_ptr<T> make_unique(Targs&& ...args) {
return std::unique_ptr<T>(new T(std::forward<Targs>(args)...));
}
class Image {
private:
uint32_t m_width;
uint32_t m_height;
uint8_t m_orientation;
std::vector<uint32_t> m_image_data;
public:
uint32_t width() {
return m_width;
}
uint32_t height() {
return m_height;
}
bool Load(std::string path) {
auto loaded = false;
auto old_warning_handler = TIFFSetWarningHandler(NULL);
auto tif = TIFFOpen(path.c_str(), "r");
TIFFSetWarningHandler(old_warning_handler);
if (tif) {
auto width = uint32_t{};
auto height = uint32_t{};
auto orientation = uint8_t{};
TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);
TIFFGetField(tif, TIFFTAG_ORIENTATION, &orientation);
orientation = (orientation > 0)
? orientation
: ORIENTATION_TOPLEFT;
auto num_pixels = width * height;
auto raster = (uint32_t*) _TIFFmalloc(num_pixels * sizeof(uint32_t));
if (raster != NULL) {
if (TIFFReadRGBAImageOriented(
tif, width, height, raster, orientation, 0)) {
m_width = width;
m_height = height;
m_orientation = orientation;
m_image_data.clear();
m_image_data.reserve(num_pixels);
for (auto i = 0; i < num_pixels; ++i) {
m_image_data.emplace_back(raster[i]);
}
loaded = true;
}
_TIFFfree(raster);
}
TIFFClose(tif);
}
return loaded;
}
bool Save(std::string path) {
auto saved = false;
auto tif = TIFFOpen(path.c_str(), "w");
if (tif) {
TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, m_width);
TIFFSetField(tif, TIFFTAG_IMAGELENGTH, m_height);
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 4);
auto orientation = (m_orientation > 0)
? m_orientation
: ORIENTATION_BOTLEFT;
TIFFSetField(tif, TIFFTAG_ORIENTATION, orientation);
TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
auto size = m_width * m_height * 4;
if (TIFFWriteEncodedStrip(tif, 0, &m_image_data[0], size)) {
saved = true;
}
TIFFClose(tif);
}
return saved;
}
uint32_t GetByte(uint32_t index) {
return m_image_data[index];
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment