1

I have a site with an image gallery (all svgs) and would like the user to be able to download them as pngs (in the future they should have a choice to save as an svg, png, jpg, or pdf, but let's handle one thing at a time).

I tried the answer found here. The file downloads as a png, but when opened I get an error that the file is damaged/corrupted.

index.html:

<a href="/path/to/file/download.php?http://example.com/uploads/icon-100.svg">
  <button> Download PNG </button>
</a>

download.php:

<?php 
  function replace_extension($filename, $new_extension) {
    $info = pathinfo($filename);
    return $info['filename'] . '.' . $new_extension;
  }

  $url = $_SERVER['QUERY_STRING'];

  header('Content-Type: application/octet-stream');
  header('Content-Disposition: attachment; filename="'.replace_extension( basename($url), 'png').'"'); 
  readfile($url);
?>

The other answers I've found only address changing the extension or renaming the file, not changing the format/type. See here.

How do I change a file format/type in php?

Thanks!

Community
  • 1
  • 1
BastionGamma
  • 321
  • 3
  • 17
  • 3
    Now is probably a good time to learn that simply changing the extension of a file doesn't change the actual content/format of that file in any way; calling a pig "orange" doesn't make it a citrus fruit of any kind, it's still a pig – Mark Baker Apr 28 '16 at 14:50
  • If you want to change the format of a file, you need to change the actual content of that file; and for changing an svg format file to a png format file is probably something you'd need to find a library to do for you – Mark Baker Apr 28 '16 at 14:51
  • 1
    http://stackoverflow.com/questions/4809194/convert-svg-image-to-png-with-php – Hamza Zafeer Apr 28 '16 at 14:56
  • @HamzaZafeer Thanks! – BastionGamma Apr 28 '16 at 14:57

1 Answers1

2

It's really not that simple. What you're doing is the equivalent of renaming a .svg file to .png on your computer, of course that won't work.

You can convert images through a library, such as ImageMagick. Likewise, you will need a different library to work with PDFs.

Community
  • 1
  • 1
mister martin
  • 6,197
  • 4
  • 30
  • 63