PHP don't recognize jpg file (from canvas)

Pedro Chagas
Pedro Chagas used Ask the Experts™
on
Hi E's,
PHP don't recognize a jpg file send to the server using jQuery ajax (obtained by canvas).
I have 2 files, index.html that take a picture, and send that picture to my server, and the file upload.php save the image in my server:
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">

    <link rel="stylesheet" href="materialize/css/materialize.min.css" />

    <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="materialize/js/materialize.min.js"></script>

    <title>Tirar Foto</title>
</head>

<body>
    <div class="row" style="margin-top: 100px;">
        <div class="col s12 center-align">
            <a class="waves-effect waves-light btn" onclick="tirar_foto();">picture</a>
            <a class="waves-effect waves-light btn" onclick="send();">send</a>
        </div>
        <div class="col s1"></div>
        <div class="col s10 center-align" style="margin-top: 25px;">
            <img id="mostra_imagem" src="" class="responsive-img" />
        </div>
        <div class="col s1"></div>
        <div class="col s12 center-align">
            <!--<a class="waves-effect waves-light btn" onclick="transformar();">Transformar</a>-->
        </div>
    </div>

    <script type="text/javascript" src="cordova.js"></script>
    <script>
        function tirar_foto() {
            var options = {
                quality: 80,
                destinationType: Camera.DestinationType.FILE_URI,
                encodingType: Camera.EncodingType.JPEG,
                mediaType: Camera.MediaType.PICTURE,
                targetWidth: 1200,
                targetHeight: 800
            }
            navigator.camera.getPicture(success, fail, options);
        }

        function success(thePicture) {
            $("#mostra_imagem").attr("src", thePicture);    
        }
        
        function fail(e) {
            alert("Image failed: " + e.message);
        } 
        
        function send(){
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');

var img = document.getElementById('mostra_imagem');
canvas.width = "1200";
canvas.height = "800";
context.drawImage(img, 0, 0 );     
        
canvas.toBlob(function(blob) {
  var fd = new FormData();
  fd.append('filename', blob, 'theimage.jpg');
  $.ajax({
    url: 'http://app.xxxxxxxxxxxxxx.com/upload.php', 
    type: 'POST',
    data: fd,
    processData: false,
    contentType: false 
  }).then(function(resp) {
    alert(resp);
  });
});

        }
            
    </script>
</body>
</html>

Open in new window

    if ( 0 < $_FILES['file']['error'] ) {
    echo 'Error: ' . $_FILES['filename']['error'] . '';
}
else {
    move_uploaded_file($_FILES['filename']['tmp_name'], 'imagem/' . $_FILES['filename']['name']);
}

$nome = $_FILES['filename']['name'];
$caminho = "imagem/" . $nome; 

if(exif_imagetype($caminho) != IMAGETYPE_JPEG){
    echo 'Not a JPEG image';
}else{
    echo "é jpg";
}

Open in new window

Like you can see in html document, I take a picture, I get that image in canvas, and I use jQuery to send the image to my server. In my server I use php to save the image to a folder, and after that I want use the image to do some transformations.
The problem is, php don't recognize the jpg image, even having the extension jpg. In php code I do a test usig function exif_imagetype, and the result is always "Not a JPEG image"!

What I have to do for php recognize jpg file? I have to change something in canvas, or have any solution in php?

The best regards, JC
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Save the image to a file and post that file here.
Pedro ChagasWebmaster

Author

Commented:
QK_1522052423749.png
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
That's a PNG image not a JPG image

if(exif_imagetype($caminho) != IMAGETYPE_PNG){
    echo 'Not a JPEG image';
}else{
    echo "é jpg";
}

Open in new window

Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Pedro ChagasWebmaster

Author

Commented:
I'm sorry, but also with jpg file they give the same answer.
Later, when I'm in home, I show to you more details.

~ JC
check your network call using inspector whether file or filename is passed in params...
if the image is passed as base64 then u need to use put file content and also check the param has right file name passed.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
The file you posted above - where did that come from?
Was that saved by the server script?
NerdsOfTechTechnology Scientist

Commented:
exif data may not be present in the image file; instead, use pathinfo() like this:

$nome = $_FILES['filename']['name'];
$caminho = "imagem/" . $nome; 

$allowed = array('jpg');
// $allowed can take on multiple values like:
// $allowed =  array('gif','png' ,'jpg');
$ext = pathinfo($nome, PATHINFO_EXTENSION);

if(!in_array($ext,$allowed) ) {
	echo 'filetype not allowed';
}else{
	echo 'filetype allowed';
}

Open in new window

Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
The file posted above does have exif data - if you run this on it
<?php
$caminho = "images/test001.png";
echo exif_imagetype($caminho);

Open in new window

The output is 3 (IMAGETYPE_PNG) - which brings me back to my original question - is the file you posted an exact copy of a file created by the upload process?
Pedro ChagasWebmaster

Author

Commented:
Hi @Julian,
I send a new image, and I think this one is a jpg.
The php still not recognize the jpg file.
the image created by the upload process
~JC
Pedro ChagasWebmaster

Author

Commented:
Hi again @Julian,
The image still a png, I checked this on properties:26-03-2018-23-24-48.jpgI don't understand why, but in the script I have this line:
encodingType: Camera.EncodingType.JPEG,
and this
fd.append('filename', blob, 'theimage.jpg');
So, It is thus concluded that it is impossible for php to recognize the file.
What might be at the source of this problem?

~JC
Technology Scientist
Commented:
Each OS has quirks with this API and some parameters may be ignored

Which OS is the camera running?

Workaround: You could easily convert the png image to jpeg, since it looks like the encoding type is being ignored by the camera's OS.

$image = imagecreatefrompng($caminho);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);
$quality = 80; // 0 = worst / smaller file, 100 = better / bigger file 
imagejpeg($bg, $caminho . ".jpg", $quality);
imagedestroy($bg);

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial