I want to create the basic form can scale and crop by php. This is my step
Process.php
<?php
// Bật báo cáo lỗi và hiển thị lỗi
error_reporting(E_ALL);
ini_set('display_errors', 1);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Nhận dữ liệu ảnh sau khi cắt từ dạng base64
$croppedImageBase64 = $_POST['croppedImage'];
// Chuyển đổi dữ liệu base64 thành tệp ảnh
$croppedImage = base64_decode(preg_replace('#^data:image/w+;base64,#i', '', $croppedImageBase64));
// Đường dẫn lưu trữ tệp ảnh đã cắt
$croppedImagePath = '/home/sam15997/public_html/test/test1/cropped_image.jpeg';
// Lưu ảnh đã cắt
if (file_put_contents($croppedImagePath, $croppedImage) === false) {
echo 'Có lỗi xảy ra khi lưu tệp ảnh.';
exit();
}
// Kiểm tra xem tệp ảnh đã cắt có tồn tại
if (!file_exists($croppedImagePath)) {
echo 'Tệp ảnh đã cắt không tồn tại.';
exit();
}
// Tải tệp ảnh đã cắt về máy tính
header('Content-Length: ' . filesize($croppedImagePath));
header('Content-Type: image/jpeg');
header('Content-Disposition: attachment; filename="cropped_image.jpeg"');
readfile($croppedImagePath);
// Xóa tệp ảnh đã cắt sau khi tải về
if (unlink($croppedImagePath) === false) {
echo 'Có lỗi xảy ra khi xóa tệp ảnh đã cắt.';
exit();
}
// Kết thúc
exit();
}
?>
And this Script.js
document.addEventListener('DOMContentLoaded', function () {
// Chọn input tải ảnh và div hiển thị ảnh và công cụ cắt
var imageInput = document.getElementById('imageInput');
var previewImage = document.getElementById('previewImage');
var imageCrop = document.getElementById('imageCrop');
// Khởi tạo CropperJS với cấu hình tùy chỉnh
var cropper = new Cropper(previewImage, {
aspectRatio: 2/3, // Kích thước 40x60 (rất tiện lợi)
zoomable: true,
scalable: true,
crop: function (e) {
// Lấy thông tin vùng cắt
var data = cropper.getData();
var croppedCanvas = cropper.getCroppedCanvas();
// Cập nhật vùng hiển thị ảnh cắt
imageCrop.innerHTML = '';
imageCrop.appendChild(croppedCanvas);
},
});
// Xử lý sự kiện khi tải ảnh lên
imageInput.addEventListener('change', function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (event) {
// Set ảnh vào CropperJS
cropper.replace(event.target.result);
};
reader.readAsDataURL(file);
});
});
But when i finish crop and download, i can’t show the image. This error: Photo can’t open this file because the format is curently unsupported or the file is corrupted. I don’t know why
Pls help me fix …