Skip to content

Instantly share code, notes, and snippets.

@mebjas
Created November 16, 2022 09:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mebjas/9fbf7f1b15b6f1e16881532f30d252bc to your computer and use it in GitHub Desktop.
Save mebjas/9fbf7f1b15b6f1e16881532f30d252bc to your computer and use it in GitHub Desktop.
Header file for our image library
#include <memory>
#include <assert.h>
#include <android/imagedecoder.h>
// Data class for ARGB image (owns the memory associated with the image).
//
// Note for readers: Current implementation only allows read operations but can
// be extended to support write operations by overloading `()=` operator.
class Image {
public:
friend class ImageFactory;
// Creating the image will allocate corresponding memory.
Image(int width, int height, int channels, int stride) :
width_(width),
height_(height),
channels_(channels),
stride_(stride) {
// Restricting the image to u8 datatype for this example.
this->pixels_ = std::make_unique<uint8_t[]>(width * height * channels);
}
// Getter: Get pixel value of image at (x, y, c).
uint8_t operator()(int x, int y, int c) const {
// TODO: add assertions? (at your own risk).
uint8_t* pixel = this->pixels_.get() + (y * stride_ + x * 4 + c);
return *pixel;
}
int width() const { return this->width_; }
int height() const { return this->height_; }
int channels() const { return this->channels_; }
int stride() const { return this->stride_; }
private:
void* pixels() {
return static_cast<void*>(this->pixels_.get());
}
std::unique_ptr<uint8_t[]> pixels_;
const int width_;
const int height_;
const int channels_;
const int stride_;
};
// Factory class for creating 'Image'.
class ImageFactory {
public:
// Creates an instance of 'Image' from the file descriptor 'fd'.
//
// Will return 'nullptr' if it's unable to decode image successfully.
//
// Note for readers: If you can add abseil package to your code base, I
// recommend changing this API to return
// 'absl::StatusOr<std::unique_ptr<Image>>' instead. This will lead to much
// cleaner API and improved error handling.
static std::unique_ptr<Image> FromFd(int fd);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment