| 49 | } |
| 50 | |
| 51 | std::shared_ptr<Image> Image::LoadResource(const std::string& resourcename, double dpiscale) |
| 52 | { |
| 53 | size_t extensionpos = resourcename.find_last_of("./\\"); |
| 54 | if (extensionpos == std::string::npos || resourcename[extensionpos] != '.') |
| 55 | throw std::runtime_error("Unsupported image format"); |
| 56 | std::string extension = resourcename.substr(extensionpos + 1); |
| 57 | for (char& c : extension) |
| 58 | { |
| 59 | if (c >= 'A' && c <= 'Z') |
| 60 | c = c - 'A' + 'a'; |
| 61 | } |
| 62 | |
| 63 | if (extension == "png") |
| 64 | { |
| 65 | auto filedata = LoadWidgetData(resourcename); |
| 66 | |
| 67 | std::vector<unsigned char> pixels; |
| 68 | unsigned long width = 0, height = 0; |
| 69 | int result = decodePNG(pixels, width, height, (const unsigned char*)filedata.data(), filedata.size(), true); |
| 70 | if (result != 0) |
| 71 | throw std::runtime_error("Could not decode PNG file"); |
| 72 | |
| 73 | return Image::Create(width, height, ImageFormat::R8G8B8A8, pixels.data()); |
| 74 | } |
| 75 | else if (extension == "svg") |
| 76 | { |
| 77 | auto filedata = LoadWidgetData(resourcename); |
| 78 | filedata.push_back(0); |
| 79 | |
| 80 | NSVGimage* svgimage = nsvgParse((char*)filedata.data(), "px", (float)(96.0 * dpiscale)); |
| 81 | if (!svgimage) |
| 82 | throw std::runtime_error("Could not parse SVG file"); |
| 83 | |
| 84 | try |
| 85 | { |
| 86 | int width = (int)(svgimage->width * dpiscale); |
| 87 | int height = (int)(svgimage->height * dpiscale); |
| 88 | std::shared_ptr<Image> image = Image::Create(width, height, ImageFormat::R8G8B8A8, nullptr); |
| 89 | |
| 90 | NSVGrasterizer* rast = nsvgCreateRasterizer(); |
| 91 | if (!rast) |
| 92 | throw std::runtime_error("Could not create SVG rasterizer"); |
| 93 | |
| 94 | nsvgRasterize(rast, svgimage, 0.0f, 0.0f, (float)dpiscale, (unsigned char*)image->GetData(), width, height, width * 4); |
| 95 | |
| 96 | nsvgDeleteRasterizer(rast); |
| 97 | nsvgDelete(svgimage); |
| 98 | return image; |
| 99 | } |
| 100 | catch (...) |
| 101 | { |
| 102 | nsvgDelete(svgimage); |
| 103 | throw; |
| 104 | } |
| 105 | } |
| 106 | else |
| 107 | { |
| 108 | throw std::runtime_error("Unsupported image format"); |
nothing calls this directly
no test coverage detected