Estiliza pagina de upload externo - responsiva (novo47)

This commit is contained in:
rodrigo committed 2025-01-28 16:31:59 -03:00
1 parent 05cd7b9c79
commit 2ef864f19e
6 files changed
+601 -1

No files matched your search

+85
View File
@@ -0,0 +1,85 @@
<?php
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
}
// Conectar ao banco de dados
$mysqli = new mysqli("10.15.0.42", "root", "34641747", "valida");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Buscar histórico de documentos processados
$query = "SELECT pd.*, u.username FROM processed_documents pd
LEFT JOIN users u ON pd.user_id = u.id
ORDER BY pd.created_at DESC";
$result = $mysqli->query($query);
?>
<div class="container">
<h2>Histórico de Documentos Processados</h2>
<table class="data-table">
<thead>
<tr>
<th>Data/Hora</th>
<th>Usuário</th>
<th>Documento Original</th>
<th>Documento Processado</th>
<th>Ações</th>
</tr>
</thead>
<tbody>
<?php while ($row = $result->fetch_assoc()): ?>
<tr>
<td><?php echo date('d/m/Y H:i:s', strtotime($row['created_at'])); ?></td>
<td><?php echo htmlspecialchars($row['username']); ?></td>
<td>
<a href="<?php echo htmlspecialchars($row['original_path']); ?>" target="_blank">
Ver Original
</a>
</td>
<td>
<a href="<?php echo htmlspecialchars($row['processed_path']); ?>" target="_blank">
Ver Processado
</a>
</td>
<td>
<button onclick="deleteDocument(<?php echo $row['id']; ?>)" class="delete-btn">
Excluir
</button>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
<script>
function deleteDocument(id) {
if (confirm('Tem certeza que deseja excluir este documento?')) {
fetch('delete_document.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({id: id})
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert('Documento excluído com sucesso!');
location.reload();
} else {
alert('Erro ao excluir documento: ' + data.message);
}
})
.catch(error => {
console.error('Error:', error);
alert('Erro ao excluir documento');
});
}
}
</script>
+372
View File
@@ -0,0 +1,372 @@
<?php
class DocumentProcessor {
private $srcImage;
private $processedImage;
private $outputPath;
public function __construct() {
if (!extension_loaded('gd')) {
throw new Exception('GD extension is required');
}
}
public function processDocument($imagePath, $outputPath) {
$this->outputPath = $outputPath;
// Detecta o tipo da imagem e carrega
$imageInfo = getimagesize($imagePath);
if ($imageInfo === false) {
throw new Exception('Failed to load image');
}
switch ($imageInfo[2]) {
case IMAGETYPE_JPEG:
$this->srcImage = imagecreatefromjpeg($imagePath);
break;
case IMAGETYPE_PNG:
$this->srcImage = imagecreatefrompng($imagePath);
break;
default:
throw new Exception('Unsupported image type');
}
if ($this->srcImage === false) {
throw new Exception('Failed to create image resource');
}
// Novo pipeline de processamento mais completo
$this->detectAndCropDocument()
->convertToGrayscale()
->enhanceContrast()
->sharpenImage()
->removeNoise()
->adjustBrightnessContrast()
->normalizeBackground()
->saveResult();
return $this->outputPath;
}
private function detectAndCropDocument() {
$width = imagesx($this->srcImage);
$height = imagesy($this->srcImage);
// Cria imagem temporária em escala de cinza
$gray = imagecreatetruecolor($width, $height);
imagecopy($gray, $this->srcImage, 0, 0, 0, 0, $width, $height);
imagefilter($gray, IMG_FILTER_GRAYSCALE);
// Aplica threshold adaptativo para binarização
$threshold = $this->getAdaptiveThreshold($gray);
$binary = imagecreatetruecolor($width, $height);
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
$rgb = imagecolorat($gray, $x, $y);
$colors = imagecolorsforindex($gray, $rgb);
$value = ($colors['red'] + $colors['green'] + $colors['blue']) / 3;
if ($value > $threshold) {
imagesetpixel($binary, $x, $y, 0xFFFFFF);
} else {
imagesetpixel($binary, $x, $y, 0x000000);
}
}
}
// Encontra os contornos do documento
$bounds = $this->findDocumentBounds($binary);
if ($bounds) {
// Adiciona margem de segurança
$margin = 10;
$cropX = max(0, $bounds['left'] - $margin);
$cropY = max(0, $bounds['top'] - $margin);
$cropWidth = min($width - $cropX, $bounds['right'] - $bounds['left'] + 2 * $margin);
for ($y = 0; $y < $height; $y += 10) {
$rgb = imagecolorat($img, $x, $y);
$colors = imagecolorsforindex($img, $rgb);
// Detecta mudanças bruscas de intensidade
if ($this->isEdgePoint($img, $x, $y)) {
$points[] = [$x, $y];
}
}
}
// Encontra os 4 cantos do documento
if (count($points) >= 4) {
return $this->findCornerPoints($points);
}
return null;
}
private function isEdgePoint($img, $x, $y) {
$threshold = 30;
// Verifica pixels vizinhos
$center = $this->getPixelIntensity($img, $x, $y);
$left = $this->getPixelIntensity($img, $x - 1, $y);
$right = $this->getPixelIntensity($img, $x + 1, $y);
$top = $this->getPixelIntensity($img, $x, $y - 1);
$bottom = $this->getPixelIntensity($img, $x, $y + 1);
return (abs($center - $left) > $threshold ||
abs($center - $right) > $threshold ||
abs($center - $top) > $threshold ||
abs($center - $bottom) > $threshold);
}
private function getPixelIntensity($img, $x, $y) {
if ($x < 0 || $y < 0 || $x >= imagesx($img) || $y >= imagesy($img)) {
return 0;
}
$rgb = imagecolorat($img, $x, $y);
$colors = imagecolorsforindex($img, $rgb);
return ($colors['red'] + $colors['green'] + $colors['blue']) / 3;
}
private function findCornerPoints($points) {
// Encontra os pontos mais extremos
$topLeft = null;
$topRight = null;
$bottomLeft = null;
$bottomRight = null;
$minSum = PHP_FLOAT_MAX;
$maxSum = PHP_FLOAT_MIN;
$minDiff = PHP_FLOAT_MAX;
$maxDiff = PHP_FLOAT_MIN;
foreach ($points as $point) {
$sum = $point[0] + $point[1];
$diff = $point[0] - $point[1];
if ($sum < $minSum) {
$minSum = $sum;
$topLeft = $point;
}
if ($sum > $maxSum) {
$maxSum = $sum;
$bottomRight = $point;
}
if ($diff < $minDiff) {
$minDiff = $diff;
$bottomLeft = $point;
}
if ($diff > $maxDiff) {
$maxDiff = $diff;
$topRight = $point;
}
}
if ($topLeft && $topRight && $bottomLeft && $bottomRight) {
return [$topLeft, $topRight, $bottomRight, $bottomLeft];
}
return null;
}
private function cropAndTransform($img, $corners) {
$width = abs($corners[1][0] - $corners[0][0]);
$height = abs($corners[3][1] - $corners[0][1]);
$dest = imagecreatetruecolor($width, $height);
// Preserva transparência
imagealphablending($dest, false);
imagesavealpha($dest, true);
// Define pontos de destino
$dest_points = [
0, 0,
$width - 1, 0,
$width - 1, $height - 1,
0, $height - 1
];
// Define pontos de origem
$src_points = [];
foreach ($corners as $corner) {
$src_points[] = $corner[0];
$src_points[] = $corner[1];
}
// Aplica transformação perspectiva
imagecopyresampled(
$dest, $img,
0, 0, min($src_points[0], $src_points[6]), min($src_points[1], $src_points[3]),
$width, $height,
max($src_points[2], $src_points[4]) - min($src_points[0], $src_points[6]),
max($src_points[5], $src_points[7]) - min($src_points[1], $src_points[3])
);
return $dest;
}
private function convertToGrayscale() {
if (!isset($this->processedImage)) {
$this->processedImage = $this->srcImage;
}
imagefilter($this->processedImage, IMG_FILTER_GRAYSCALE);
return $this;
}
private function enhanceContrast() {
// Aplica equalização de histograma adaptativa
$width = imagesx($this->processedImage);
$height = imagesy($this->processedImage);
// Divide a imagem em blocos e aplica equalização local
$blockSize = 32;
for ($x = 0; $x < $width; $x += $blockSize) {
for ($y = 0; $y < $height; $y += $blockSize) {
$this->equalizeHistogramBlock($x, $y, min($blockSize, $width - $x), min($blockSize, $height - $y));
}
}
return $this;
}
private function equalizeHistogramBlock($startX, $startY, $blockWidth, $blockHeight) {
$histogram = array_fill(0, 256, 0);
$total = 0;
// Calcula histograma do bloco
for ($x = $startX; $x < $startX + $blockWidth; $x++) {
for ($y = $startY; $y < $startY + $blockHeight; $y++) {
$rgb = imagecolorat($this->processedImage, $x, $y);
$colors = imagecolorsforindex($this->processedImage, $rgb);
$gray = $colors['red']; // Já está em escala de cinza
$histogram[$gray]++;
$total++;
}
}
// Calcula LUT de equalização
$lut = array();
$sum = 0;
for ($i = 0; $i < 256; $i++) {
$sum += $histogram[$i];
$lut[$i] = round(($sum * 255) / $total);
}
// Aplica equalização
for ($x = $startX; $x < $startX + $blockWidth; $x++) {
for ($y = $startY; $y < $startY + $blockHeight; $y++) {
$rgb = imagecolorat($this->processedImage, $x, $y);
$colors = imagecolorsforindex($this->processedImage, $rgb);
$newGray = $lut[$colors['red']];
$color = imagecolorallocate($this->processedImage, $newGray, $newGray, $newGray);
imagesetpixel($this->processedImage, $x, $y, $color);
}
}
}
private function sharpenImage() {
// Matriz de convolução para sharpening
$sharpenMatrix = [
[-1, -1, -1],
[-1, 9, -1],
[-1, -1, -1]
];
$this->applyConvolution($sharpenMatrix);
return $this;
}
private function removeNoise() {
// Aplica filtro mediano
$temp = imagecreatetruecolor(imagesx($this->processedImage), imagesy($this->processedImage));
imagecopy($temp, $this->processedImage, 0, 0, 0, 0, imagesx($this->processedImage), imagesy($this->processedImage));
for ($x = 1; $x < imagesx($this->processedImage) - 1; $x++) {
for ($y = 1; $y < imagesy($this->processedImage) - 1; $y++) {
$values = array();
// Coleta valores dos pixels vizinhos
for ($i = -1; $i <= 1; $i++) {
for ($j = -1; $j <= 1; $j++) {
$rgb = imagecolorat($temp, $x + $i, $y + $j);
$colors = imagecolorsforindex($temp, $rgb);
$values[] = $colors['red'];
}
}
sort($values);
$median = $values[4]; // Valor mediano
$color = imagecolorallocate($this->processedImage, $median, $median, $median);
imagesetpixel($this->processedImage, $x, $y, $color);
}
}
imagedestroy($temp);
return $this;
}
private function adjustBrightnessContrast() {
// Ajusta brilho automaticamente
imagefilter($this->processedImage, IMG_FILTER_BRIGHTNESS, 10);
imagefilter($this->processedImage, IMG_FILTER_CONTRAST, -10);
return $this;
}
private function normalizeBackground() {
$width = imagesx($this->processedImage);
$height = imagesy($this->processedImage);
// Detecta cor do fundo (assume que os cantos são fundo)
$cornerColors = array();
$cornerColors[] = imagecolorat($this->processedImage, 0, 0);
$cornerColors[] = imagecolorat($this->processedImage, $width-1, 0);
$cornerColors[] = imagecolorat($this->processedImage, 0, $height-1);
$cornerColors[] = imagecolorat($this->processedImage, $width-1, $height-1);
// Calcula cor média do fundo
$avgBackground = 255; // Assumimos fundo branco
// Normaliza fundo
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
$rgb = imagecolorat($this->processedImage, $x, $y);
$colors = imagecolorsforindex($this->processedImage, $rgb);
if ($colors['red'] > $avgBackground - 30) { // Se for próximo do fundo
$color = imagecolorallocate($this->processedImage, 255, 255, 255);
imagesetpixel($this->processedImage, $x, $y, $color);
}
}
}
return $this;
}
private function saveResult() {
if (!isset($this->processedImage)) {
throw new Exception('No processed image to save');
}
$extension = strtolower(pathinfo($this->outputPath, PATHINFO_EXTENSION));
switch ($extension) {
case 'jpg':
case 'jpeg':
imagejpeg($this->processedImage, $this->outputPath, 90);
break;
case 'png':
imagepng($this->processedImage, $this->outputPath, 9);
break;
default:
throw new Exception('Unsupported output image type');
}
if (is_resource($this->srcImage)) {
imagedestroy($this->srcImage);
}
if (is_resource($this->processedImage)) {
imagedestroy($this->processedImage);
}
return $this;
}
}
+4
View File
@@ -52,6 +52,10 @@ include 'top_menu.php';
include 'clientes/edit_note.php'; include 'clientes/edit_note.php';
} elseif ($page == 'delete_note' && isset($_POST['id'])) { } elseif ($page == 'delete_note' && isset($_POST['id'])) {
include 'clientes/delete_note.php'; include 'clientes/delete_note.php';
} elseif ($page == 'process_document') {
include 'process_document.php';
} elseif ($page == 'document_history') {
include 'document_history.php';
} else { } else {
echo "<h2>Bem-vindo ao Sistema de Ferramentas</h2>"; echo "<h2>Bem-vindo ao Sistema de Ferramentas</h2>";
} }
+8 -1
View File
@@ -12,7 +12,7 @@ if (!isset($_SESSION['user_id'])) {
<li> <li>
<a href="javascript:void(0);" onclick="toggleSubmenu('submenu1')">Autenticador de Provas Digitais</a> <a href="javascript:void(0);" onclick="toggleSubmenu('submenu1')">Autenticador de Provas Digitais</a>
<ul id="submenu1" class="submenu"> <ul id="submenu1" class="submenu">
<li><a href="index.php?page=upload">Upload de Arquivos</a></li> <li><a href="/prova/upload_prova.php">Upload de Arquivos</a></li>
<li><a href="index.php?page=status">Ver Status</a></li> <li><a href="index.php?page=status">Ver Status</a></li>
<li><a href="index.php?page=list_files">Lista de Arquivos Processados</a></li> <li><a href="index.php?page=list_files">Lista de Arquivos Processados</a></li>
</ul> </ul>
@@ -24,6 +24,13 @@ if (!isset($_SESSION['user_id'])) {
<li><a href="index.php?page=list_clients">Listagem de Clientes</a></li> <li><a href="index.php?page=list_clients">Listagem de Clientes</a></li>
</ul> </ul>
</li> </li>
<li>
<a href="javascript:void(0);" onclick="toggleSubmenu('submenu3')">Processamento de Documentos</a>
<ul id="submenu3" class="submenu">
<li><a href="index.php?page=process_document">Processar Documento</a></li>
<li><a href="index.php?page=document_history">Histórico</a></li>
</ul>
</li>
<!-- Adicione mais ferramentas aqui --> <!-- Adicione mais ferramentas aqui -->
</ul> </ul>
</div> </div>
+85
View File
@@ -0,0 +1,85 @@
<?php
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
}
require_once 'document_processor.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['document'])) {
try {
$file = $_FILES['document'];
$uploadDir = 'uploads/documents/';
$processedDir = 'uploads/processed/';
// Cria diretórios se não existirem
if (!file_exists($uploadDir)) {
mkdir($uploadDir, 0777, true);
}
if (!file_exists($processedDir)) {
mkdir($processedDir, 0777, true);
}
// Gera nomes únicos para os arquivos
$originalName = basename($file['name']);
$extension = pathinfo($originalName, PATHINFO_EXTENSION);
$timestamp = time();
$uploadFile = $uploadDir . $timestamp . '_' . $originalName;
$processedFile = $processedDir . $timestamp . '_processed.' . $extension;
if (move_uploaded_file($file['tmp_name'], $uploadFile)) {
$processor = new DocumentProcessor();
$result = $processor->processDocument($uploadFile, $processedFile);
// Salva o registro no banco de dados
$mysqli = new mysqli("10.15.0.42", "root", "34641747", "valida");
$stmt = $mysqli->prepare("INSERT INTO processed_documents (user_id, original_path, processed_path, created_at) VALUES (?, ?, ?, NOW())");
$stmt->bind_param("iss", $_SESSION['user_id'], $uploadFile, $processedFile);
$stmt->execute();
$message = "Documento processado com sucesso!";
$success = true;
} else {
throw new Exception("Falha ao fazer upload do arquivo.");
}
} catch (Exception $e) {
$message = "Erro: " . $e->getMessage();
$success = false;
}
}
?>
<div class="container">
<h2>Processamento de Documentos</h2>
<?php if (isset($message)): ?>
<div class="alert <?php echo $success ? 'alert-success' : 'alert-error'; ?>">
<?php echo htmlspecialchars($message); ?>
</div>
<?php endif; ?>
<form method="POST" enctype="multipart/form-data" class="upload-form">
<div class="form-group">
<label for="document">Selecione o documento:</label>
<input type="file" id="document" name="document" accept="image/*" required>
</div>
<button type="submit" class="btn btn-primary">Processar Documento</button>
</form>
<?php if (isset($processedFile) && file_exists($processedFile)): ?>
<div class="result-preview">
<h3>Resultado:</h3>
<div class="image-comparison">
<div>
<h4>Original:</h4>
<img src="<?php echo htmlspecialchars($uploadFile); ?>" alt="Original">
</div>
<div>
<h4>Processado:</h4>
<img src="<?php echo htmlspecialchars($processedFile); ?>" alt="Processado">
</div>
</div>
</div>
<?php endif; ?>
</div>
+47
View File
@@ -209,3 +209,50 @@ textarea {
#search-button:hover { #search-button:hover {
background-color: #0056b3; background-color: #0056b3;
} }
/* Estilos para processamento de documentos */
.upload-form {
max-width: 600px;
margin: 20px auto;
padding: 20px;
background: #f5f5f5;
border-radius: 5px;
}
.result-preview {
margin-top: 30px;
}
.image-comparison {
display: flex;
justify-content: space-around;
margin-top: 20px;
flex-wrap: wrap;
}
.image-comparison img {
max-width: 45%;
height: auto;
margin: 10px;
border: 1px solid #ddd;
box-shadow: 0 0 5px rgba(0,0,0,0.2);
}
.alert {
padding: 15px;
margin-bottom: 20px;
border: 1px solid transparent;
border-radius: 4px;
}
.alert-success {
color: #155724;
background-color: #d4edda;
border-color: #c3e6cb;
}
.alert-error {
color: #721c24;
background-color: #f8d7da;
border-color: #f5c6cb;
}