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/2608315e3d4a97775d729334f4ccee3c to your computer and use it in GitHub Desktop.
Save mebjas/2608315e3d4a97775d729334f4ccee3c to your computer and use it in GitHub Desktop.
Implementation of ImageFactory in image library
#include "image.h"
#include <android/imagedecoder.h>
static std::unique_ptr<Image> ImageFactory::FromFd(int fd) {
// First create decoder from fd.
AImageDecoder* decoder;
int result = AImageDecoder_createFromFd(fd, &decoder);
if (result != ANDROID_IMAGE_DECODER_SUCCESS) {
// More info: https://developer.android.com/ndk/reference/group/image-decoder#aimagedecoder_createfromfd
// Not a good idea to opaquely consume the error, it'd be a good idea to
// use StatusOr from abseil package: https://abseil.io/
return nullptr;
}
// Lambda for cleaning up the decoder when exiting.
auto decoder_cleanup = [&decoder] () {
AImageDecoder_delete(decoder);
};
const AImageDecoderHeaderInfo* header_info = AImageDecoder_getHeaderInfo(decoder);
int bitmap_format = AImageDecoderHeaderInfo_getAndroidBitmapFormat(header_info);
// This is just for example. I don't want to handle other cases in this
// example, but that should be easy enough to do.
if (bitmap_format != ANDROID_BITMAP_FORMAT_RGBA_8888) {
decoder_cleanup();
return nullptr;
}
constexpr int kChannels = 4;
int width = AImageDecoderHeaderInfo_getWidth(header_info);
int height = AImageDecoderHeaderInfo_getHeight(header_info);
size_t stride = AImageDecoder_getMinimumStride(decoder);
std::unique_ptr<Image> image_ptr = std::make_unique<Image>(
width, height, kChannels, stride);
size_t size = width * height * kChannels;
int decode_result = AImageDecoder_decodeImage(
decoder, image_ptr->pixels(), stride, size);
if (decode_result != ANDROID_IMAGE_DECODER_SUCCESS) {
decoder_cleanup();
return nullptr;
}
decoder_cleanup();
return image_ptr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment