Home >Backend Development >PHP Tutorial >Why Are My HTML5 Canvas Images Corrupted When Saving to the Server?

Why Are My HTML5 Canvas Images Corrupted When Saving to the Server?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-27 09:48:10798browse

Why Are My HTML5 Canvas Images Corrupted When Saving to the Server?

Troubleshooting Saving an HTML5 Canvas as an Image on the Server

Problem

After following online tutorials, attempts to save an HTML5 Canvas as an image on the server result in corrupted or empty files. The cause remains unknown.

Solution

1. Configure the XMLHttpRequest correctly:

  • Replace the custom XMLHttpRequest creation with the following to support both old and modern browsers:
var xmlHttpReq = false;
if (window.XMLHttpRequest) {
  ajax = new XMLHttpRequest();
} else if (window.ActiveXObject) {
  ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
  • Set the Content-Type to application/x-www-form-urlencoded:
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

2. Modify the PHP Script:

  • Change substr($imageData, strpos($imageData, ",")) to substr($imageData, strpos($imageData, ",")) 1.
  • Handle potential errors by checking if the file handle is valid before writing:
if ($fp) {
  fwrite($fp, $unencodedData);
  fclose($fp);
}

Revised JavaScript and PHP Code:

JavaScript

function saveImage() {
  var canvasData = canvas.toDataURL("image/png");
  var xmlHttpReq = false;

  if (window.XMLHttpRequest) {
    ajax = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    ajax = new ActiveXObject("Microsoft.XMLHTTP");
  }

  ajax.open("POST", "testSave.php", false);
  ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  ajax.onreadystatechange = function() {
    console.log(ajax.responseText);
  }
  ajax.send("imgData=" + canvasData);
}

PHP

<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
  $imageData = $GLOBALS['HTTP_RAW_POST_DATA'];
  $filteredData = substr($imageData, strpos($imageData, ",")+1);
  $unencodedData = base64_decode($filteredData);

  if ($fp = fopen('/path/to/file.png', 'wb')) {
    fwrite($fp, $unencodedData);
    fclose($fp);
  }
}
?>

The above is the detailed content of Why Are My HTML5 Canvas Images Corrupted When Saving to the Server?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn