| 81 | }; |
| 82 | |
| 83 | Valdi::Result<Valdi::Ref<Valdi::IBitmap>> rasterizeSVG(const Valdi::BytesView& data, |
| 84 | const Valdi::Ref<Valdi::IBitmapFactory>& bitmapFactory, |
| 85 | int preferredWidth, |
| 86 | int preferredHeight) { |
| 87 | if (bitmapFactory == nullptr) { |
| 88 | return Valdi::Error("SVG rasterization requires a bitmap factory"); |
| 89 | } |
| 90 | |
| 91 | auto dom = makeSVGDOM(data); |
| 92 | if (!dom) { |
| 93 | return dom.moveError(); |
| 94 | } |
| 95 | |
| 96 | auto intrinsicSize = dom.value()->containerSize(); |
| 97 | auto intrinsicWidth = intrinsicSize.width(); |
| 98 | auto intrinsicHeight = intrinsicSize.height(); |
| 99 | |
| 100 | if (preferredWidth > 0 && preferredHeight <= 0 && intrinsicWidth > 0 && intrinsicHeight > 0) { |
| 101 | preferredHeight = static_cast<int>(std::ceil(preferredWidth * intrinsicHeight / intrinsicWidth)); |
| 102 | } else if (preferredHeight > 0 && preferredWidth <= 0 && intrinsicWidth > 0 && intrinsicHeight > 0) { |
| 103 | preferredWidth = static_cast<int>(std::ceil(preferredHeight * intrinsicWidth / intrinsicHeight)); |
| 104 | } |
| 105 | |
| 106 | auto outputWidth = resolveSVGDimension(preferredWidth, intrinsicWidth); |
| 107 | auto outputHeight = resolveSVGDimension(preferredHeight, intrinsicHeight); |
| 108 | if (outputWidth <= 0 || outputHeight <= 0) { |
| 109 | return Valdi::Error("SVG doesn't have a valid size"); |
| 110 | } |
| 111 | |
| 112 | auto bitmap = bitmapFactory->createBitmap(outputWidth, outputHeight); |
| 113 | if (!bitmap) { |
| 114 | return bitmap.error().rethrow("Failed to create SVG rasterization bitmap: "); |
| 115 | } |
| 116 | |
| 117 | auto outputBitmap = bitmap.moveValue(); |
| 118 | auto bitmapInfo = outputBitmap->getInfo(); |
| 119 | if (bitmapInfo.width != outputWidth || bitmapInfo.height != outputHeight) { |
| 120 | return Valdi::Error("SVG rasterization bitmap factory returned an unexpected bitmap size"); |
| 121 | } |
| 122 | |
| 123 | ScopedBitmapLock bitmapLock(outputBitmap); |
| 124 | if (bitmapLock.bytes() == nullptr) { |
| 125 | return Valdi::Error("Failed to lock SVG rasterization bitmap bytes"); |
| 126 | } |
| 127 | |
| 128 | auto surface = SkSurfaces::WrapPixels(toSkiaImageInfo(bitmapInfo), bitmapLock.bytes(), bitmapInfo.rowBytes); |
| 129 | if (!surface) { |
| 130 | return Valdi::Error("Unable to create SVG rasterization surface"); |
| 131 | } |
| 132 | |
| 133 | auto* canvas = surface->getCanvas(); |
| 134 | canvas->clear(SK_ColorTRANSPARENT); |
| 135 | |
| 136 | if (intrinsicWidth > 0 && intrinsicHeight > 0) { |
| 137 | canvas->scale(static_cast<SkScalar>(outputWidth) / intrinsicWidth, |
| 138 | static_cast<SkScalar>(outputHeight) / intrinsicHeight); |
| 139 | dom.value()->setContainerSize(intrinsicSize); |
| 140 | } else { |