简体   繁体   中英

How do I Change a File's Format in PHP?

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM