本地文件上传 -> 画布灰度和缩小 -> ocr.space



大家好。我在这方面有点新手。

我想在本地选择一个文件->灰度和缩小它(因为它通常来自移动设备)->然后上传到ocr.space

以下是我迄今为止在缩小规模方面所做的:

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>

到目前为止,我如何使用以下代码将其发送到OCR:(我的OCR代码接受文件输入,但我有一个画布,因为我需要先缩小它的规模)。

<?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 GuzzleHttpClient();
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;
}
?>

我写这个答案是为了澄清如何应用我之前评论中引用的信息。您根本不会使用$_FILES变量。相反,您将通过ajax将画布作为数据url发布在普通变量中,并通过$_POST变量访问它。然后你将处理这个数据url以获得二进制图像,并用它做任何你想做的事情,即将其保存到文件中,发布到ocr服务,等等。

客户端的以下代码使用jquery,您必须在同一目录中下载它,或者用公共可用url(CDN)替换src属性:

<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>

php脚本应该是这样的:

<?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 ...
?>

相关内容

  • 没有找到相关文章

最新更新