0

Hi all you fantastic people. I'm a bit of a newbie on this.

I want to local select a file -> greyscale and downscale it (because it offen comes from a mobile devices) -> And then upload it to the ocr.space

Here is what I have so far on downscale:

var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');

function handleImage(e){
    var reader = new FileReader();
    reader.onload = function(event){
        var img = new Image();
        img.onload = function(){

        canvas.width=800
        canvas.height=600
        
        ctx.drawImage(img, 0, 0, 800, 600);
        }
        img.src = event.target.result;
    }
    reader.readAsDataURL(e.target.files[0]);     
}
<html>
    <head>
        <title>Upload PNG, JPG file</title>
    </head>
    <body>

<label>Image File:</label><br/>
<input type="file" id="imageLoader" name="imageLoader"/>
<canvas id="imageCanvas" name="imageCanvas"></canvas>

    </body>

</html>

How do I send it to OCR with the following code so far: (My OCR code takes file input, but I have a canvas because I need to downscale it first).

<?php
if(isset($_POST['submit']) && isset($_FILES)) {
    require __DIR__ . '/vendor/autoload.php';
    $target_dir = "uploads/";
    $uploadOk = 1;
    $FileType = strtolower(pathinfo($_FILES["attachment"]["name"],PATHINFO_EXTENSION));
    $target_file = $target_dir . generateRandomString() .'.'.$FileType;
    // Check file size
    
    if ($_FILES["attachment"]["size"] > 990000) {
        header('HTTP/1.0 403 Forbidden');
        echo "Beklager, filen er desværre for stor";
        $uploadOk = 0;
    }
    /*if($FileType != "png" && $FileType != "jpg") {
        header('HTTP/1.0 403 Forbidden');
        echo "Beklager, det skal være en jpg, jpeg eller png fil";
        $uploadOk = 0;
    }*/
    if ($uploadOk == 1) {
   
        if (move_uploaded_file($_FILES["attachment"]["tmp_name"], $target_file)) {
            uploadToApi($target_file);
        } else {
            header('HTTP/1.0 403 Forbidden');
            echo "Beklager, der skete en fejl da foto blev uploadet.";
        }
    } 
} else {
    header('HTTP/1.0 403 Forbidden');
    echo "Beklager, venligst upload en fil";
}

function uploadToApi($target_file){
    require __DIR__ . '/vendor/autoload.php';
    $fileData = fopen($target_file, 'r');
    $client = new \GuzzleHttp\Client();
    try {
    $r = $client->request('POST', 'https://api.ocr.space/parse/image',[
        'headers' => ['apiKey' => 'xxxxxxxx'],
        'multipart' => [
            [
                'name' => 'file',
                'contents' => $fileData
            ]
        ]
    ], ['file' => $fileData]);
    $response =  json_decode($r->getBody(),true);
    if($response['ErrorMessage'] == "") {
?>
<html>
    <head>
    <title>Result</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/css/bootstrap.min.css">
        <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
        <script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/js/bootstrap.min.js'></script>
    </head>
    <body>
        <div class="form-group container">
            <label for="exampleTextarea">Result</label>

        <input type="text" id="nummerplade" name="nummerplade" value="<?php foreach($response['ParsedResults'] as $pareValue) {echo $pareValue['ParsedText'];}?>">
        <textarea class="form-control" id="exampleTextarea" rows="30"><?php foreach($response['ParsedResults'] as $pareValue) {echo $pareValue['ParsedText'];}?></textarea>
        </div>
    </body>
</html>
<?php
    } else {
        header('HTTP/1.0 400 Forbidden');
        echo $response['ErrorMessage'];
    }
    } catch(Exception $err) {
        header('HTTP/1.0 403 Forbidden');
        echo $err->getMessage();
    }
}

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
?>
chrpust
  • 17
  • 1
  • 2
  • 7
  • Duplicate of [How to save an HTML5 Canvas as an image on a server?](https://stackoverflow.com/questions/13198131/how-to-save-an-html5-canvas-as-an-image-on-a-server) – Daniels118 Oct 13 '21 at 13:12
  • Could be but I'm totally stocked! I send it to server on: if(isset($_POST['submit']) && isset($_FILES)) { require __DIR__ . '/vendor/autoload.php'; $target_dir = "uploads/"; $uploadOk = 1; $FileType = strtolower(pathinfo($_FILES["attachment"]["name"],PATHINFO_EXTENSION)); $target_file = $target_dir . generateRandomString() .'.'.$FileType; But how do I get from canvas to upload to take uploaded file and send to ocr :) And thank you for reply Daniels118 – chrpust Oct 13 '21 at 13:42

1 Answers1

1

I'm writing this answer to clarify how to apply the information referenced in my previous comment. You won't use the $_FILES variable at all. You will instead post your canvas as a data url in a normal variable through ajax and you will access it through the $_POST variable. Then you will process this data url to get the binary image and do everuting you want with it, i.e. save it to a file, post it to ocr service, etc.

The following code on the client side uses jquery, you have to download it in the same dir or replace the src attribute with a public available url (CDN):

<html>
    <head>
        <script src="jquery-3.6.0.min.js"></script>
        <script>
$(function() {
    var imageLoader = document.getElementById('imageLoader');
    imageLoader.addEventListener('change', handleImage, false);
    var canvas = document.getElementById('imageCanvas');
    var ctx = canvas.getContext('2d');

    function handleImage(e) {
        var reader = new FileReader();
        reader.onload = function(event) {
            var img = new Image();
            img.onload = function() {
                canvas.width=80
                canvas.height=60
                ctx.drawImage(img, 0, 0, 80, 60);
            }
            img.src = event.target.result;
        }
        reader.readAsDataURL(e.target.files[0]);     
    }
    
    $('#upload').click(function() {
        var canvasData = canvas.toDataURL("image/png");
        $.ajax({
            type: "POST",
            url: "script.php",
            data: { 
                imgBase64: canvasData
            }
        }).done(function(o) {
            alert('Image sent to the server');
        });
    });
});
        </script>
    </head>
    <body>
        <label>Image File:</label><br/>
        <input type="file" id="imageLoader" name="imageLoader"/>
        <canvas id="imageCanvas" name="imageCanvas"></canvas>
        <button id="upload">Upload</button>
    </body>
</html>

The php script should be like this:

<?php
    $img = $_POST['imgBase64'];
    $img = str_replace('data:image/png;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $fileData = base64_decode($img);
    
    //... do anything you want with $fileData ...
?>
Daniels118
  • 1,149
  • 1
  • 8
  • 17