SVG.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Preview;
  8. use OCP\Files\File;
  9. use OCP\IImage;
  10. use Psr\Log\LoggerInterface;
  11. class SVG extends ProviderV2 {
  12. /**
  13. * {@inheritDoc}
  14. */
  15. public function getMimeType(): string {
  16. return '/image\/svg\+xml/';
  17. }
  18. /**
  19. * {@inheritDoc}
  20. */
  21. public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
  22. try {
  23. $content = stream_get_contents($file->fopen('r'));
  24. if (substr($content, 0, 5) !== '<?xml') {
  25. $content = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . $content;
  26. }
  27. // Do not parse SVG files with references
  28. if (preg_match('/["\s](xlink:)?href\s*=/i', $content)) {
  29. return null;
  30. }
  31. $svg = new \Imagick();
  32. $svg->pingImageBlob($content);
  33. $mimeType = $svg->getImageMimeType();
  34. if (!preg_match($this->getMimeType(), $mimeType)) {
  35. throw new \Exception('File mime type does not match the preview provider: ' . $mimeType);
  36. }
  37. $svg->setBackgroundColor(new \ImagickPixel('transparent'));
  38. $svg->readImageBlob($content);
  39. $svg->setImageFormat('png32');
  40. } catch (\Exception $e) {
  41. \OC::$server->get(LoggerInterface::class)->error(
  42. 'File: ' . $file->getPath() . ' Imagick says:',
  43. [
  44. 'exception' => $e,
  45. 'app' => 'core',
  46. ]
  47. );
  48. return null;
  49. }
  50. //new image object
  51. $image = new \OCP\Image();
  52. $image->loadFromData((string)$svg);
  53. //check if image object is valid
  54. if ($image->valid()) {
  55. $image->scaleDownToFit($maxX, $maxY);
  56. return $image;
  57. }
  58. return null;
  59. }
  60. }