Skip to content

better error handling in encodeImageData #2977

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions packages/skia/cpp/api/JsiSkImage.h
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ class JsiSkImage : public JsiSkWrappingSkPtrHostObject<SkImage> {
std::make_shared<JsiSkShader>(getContext(), std::move(shader)));
}

sk_sp<SkData> encodeImageData(const jsi::Value *arguments, size_t count) {
sk_sp<SkData> encodeImageData(const jsi::Value *arguments, size_t count, bool rasterIfNeeded) {
// Get optional parameters
auto format =
count >= 1 ? static_cast<SkEncodedImageFormat>(arguments[0].asNumber())
Expand All @@ -116,12 +116,14 @@ class JsiSkImage : public JsiSkWrappingSkPtrHostObject<SkImage> {
#if defined(SK_GRAPHITE)
image = DawnContext::getInstance().MakeRasterImage(image);
#else
if (image->isTextureBacked()) {
if (image->isTextureBacked() && rasterIfNeeded) {
auto grContext = getContext()->getDirectContext();
image = image->makeRasterImage(grContext);
if (!image) {
return nullptr;
throw std::runtime_error("Failed to create raster image from texture in encodeImageData");
}
} else if (image->isTextureBacked() && !rasterIfNeeded) {
throw std::runtime_error("Cannot encode texture-backed image directly");
}
#endif
sk_sp<SkData> data;
Expand All @@ -144,12 +146,15 @@ class JsiSkImage : public JsiSkWrappingSkPtrHostObject<SkImage> {
SkPngEncoder::Options options;
data = SkPngEncoder::Encode(nullptr, image.get(), options);
}

if (data == nullptr) {
throw std::runtime_error("Failed to encode image data or read pixels from the image");
}
return data;
}

JSI_HOST_FUNCTION(encodeToBytes) {
auto data = encodeImageData(arguments, count);
bool rasterIfNeeded = count > 0 && arguments[0].isBool() ? arguments[0].asBool() : true;
auto data = encodeImageData(arguments, count, rasterIfNeeded);
if (!data) {
return jsi::Value::null();
}
Expand All @@ -172,7 +177,8 @@ class JsiSkImage : public JsiSkWrappingSkPtrHostObject<SkImage> {
}

JSI_HOST_FUNCTION(encodeToBase64) {
auto data = encodeImageData(arguments, count);
bool rasterIfNeeded = count > 0 && arguments[0].isBool() ? arguments[0].asBool() : true;
auto data = encodeImageData(arguments, count, rasterIfNeeded);
if (!data) {
return jsi::Value::null();
}
Expand Down
Loading