<div class="container">
<div class="row">
<form action="<?php echo base_url();?>product-compress" method="post" enctype="multipart/form-data" onsubmit="return handleFiles()" >
<input type="file" name="images" value="" id="imagefile" class="btn btn-default">
<input type="submit" name="submit" value="submit" class="btn btn-default">
<input type="hidden" id="my_hidden" name="my_hidden" value="">
</form>
</div>
</div>
<img src="" id="image">
<script>
function handleFiles()
{
var filesToUpload = document.getElementById("imagefile").files;
var file = filesToUpload[0];
// Create an image
var img = document.createElement("img");
// Create a file reader
var reader = new FileReader();
// Set the image once loaded into file reader
var canvas = document.createElement('canvas');
reader.onload = function (e)
{
img.src = e.target.result;
//var canvas = document.createElement("canvas");
//var canvas = $("<canvas>", {"id":"testing"})[0];
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 400;
var MAX_HEIGHT = 300;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/png");
document.getElementById('image').src = dataurl;
};
// Load files into file reader
reader.readAsDataURL(file);
document.getElementById('my_hidden').value = canvas.toDataURL('image/png');
return true;
// Post the data
/*
var fd = new FormData();
fd.append("name", "some_filename.jpg");
fd.append("image", dataurl);
fd.append("info", "lah_de_dah");
*/
}
</script>
Server Side Code :
public function product_compress() {
$upload_dir = "uploads/products/images/"; //implement this function yourself
$img = $_POST['my_hidden'];
// echo $upload_dir."<br>";
// print_r($img);exit;
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir .time()."image_name.jpg";
$success = file_put_contents($file, $data);
//if (move_uploaded_file($_FILES["image1"]["tmp_name"], $target_file)) {
// header('Location: image-testing');
}
I got all this from stackoverflow with search for compressing a image in client side. Now i am getting a result of black colored image. It seems like i missing something for image to compress. No particular type of image conditions . if the image size 5mb i wanted into be reduced using canvas and i have find the maximum part from here