Cropping Images in the Browser Before the Upload

Upload and crop image before sending it to the server

jcrop

Jcrop is the quick and easy way to add image cropping functionality to your web application. It combines the ease-of-use of a typical jQuery plugin with a powerful cross-platform DHTML cropping engine that is faithful to familiar desktop graphics applications.

Cropping an Image In The Browser Automatically

Say this as max_size.php

<?php header('Content-type: image/jpeg');
function resampleimage($maxsize, $sourcefile, $imgcomp=0){
$g_imgcomp=100-$imgcomp;
if(file_exists($sourcefile)){
$g_is=getimagesize($sourcefile);
if($g_is[0] <= $maxsize && $g_is[1] <= $maxsize){
$new_width=$g_is[0];
$new_height=$g_is[1];
} else {
$w_adjust = ($maxsize / $g_is[0]);
$h_adjust = ($maxsize / $g_is[1]);
if($w_adjust <= $h_adjust){
$new_width=($g_is[0]*$w_adjust);
$new_height=($g_is[1]*$w_adjust);
} else {
$new_width=($g_is[0]*$h_adjust);
$new_height=($g_is[1]*$h_adjust);
}
}
$image_type = strtolower(strrchr($sourcefile, "."));

switch($image_type) {
case '.jpg':
$img_src = imagecreatefromjpeg($sourcefile);
break;
case '.jpeg':
$img_src = imagecreatefromjpeg($sourcefile);
break;
case '.png':
$img_src = imagecreatefrompng($sourcefile);
break;
case '.gif':
$img_src = imagecreatefromgif($sourcefile);
break;
default:
echo("Error Invalid Image Type");
die;
break;
}
$img_dst=imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $new_width, $new_height, $g_is[0], $g_is[1]);
imagejpeg($img_dst);
imagedestroy($img_dst);
return true;
} else {
return false;
}
}
resampleimage($_GET['maxsize'], $_GET['source']);
?>

In the page where you have image

<img id="img" src="max_size.php?maxsize=152&source=[some image path]" />

Use HTML5 to resize an image before upload

Here is what I ended up doing and it worked great.

First I moved the file input outside of the form so that it is not submitted:

<input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos(\'#{imageUploadUrl}\')" />
<form id="uploadImageForm" enctype="multipart/form-data">
<input id="name" value="#{name}" />
... a few more inputs ...
</form>

Then I changed the uploadPhotos function to handle only the resizing:

window.uploadPhotos = function(url){
// Read in file
var file = event.target.files[0];

// Ensure it's an image
if(file.type.match(/image.*/)) {
console.log('An image has been loaded');

// Load the image
var reader = new FileReader();
reader.onload = function (readerEvent) {
var image = new Image();
image.onload = function (imageEvent) {

// Resize the image
var canvas = document.createElement('canvas'),
max_size = 544,// TODO : pull max size from a site config
width = image.width,
height = image.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
var resizedImage = dataURLToBlob(dataUrl);
$.event.trigger({
type: "imageResized",
blob: resizedImage,
url: dataUrl
});
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(file);
}
};

As you can see I'm using canvas.toDataURL('image/jpeg'); to change the resized image into a dataUrl adn then I call the function dataURLToBlob(dataUrl); to turn the dataUrl into a blob that I can then append to the form. When the blob is created, I trigger a custom event. Here is the function to create the blob:

/* Utility function to convert a canvas to a BLOB */
var dataURLToBlob = function(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = parts[1];

return new Blob([raw], {type: contentType});
}

var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;

var uInt8Array = new Uint8Array(rawLength);

for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}

return new Blob([uInt8Array], {type: contentType});
}
/* End Utility function to convert a canvas to a BLOB */

Finally, here is my event handler that takes the blob from the custom event, appends the form and then submits it.

/* Handle image resized events */
$(document).on("imageResized", function (event) {
var data = new FormData($("form[id*='uploadImageForm']")[0]);
if (event.blob && event.url) {
data.append('image_data', event.blob);

$.ajax({
url: event.url,
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
//handle errors...
}
});
}
});

Cropping images client side through browser with JavaScript

You can do this by loading the image into a Canvas element and then manipulating the Canvas

Basic tutorial here

http://www.w3schools.com/html/html5_canvas.asp

(plenty more available)

Preview an image and crop it before it's uploaded

http://html5.sapnagroup.com/demos/dragDropUploadsCrop/
This link will guide what you want
http://html5.sapnagroup.com/2012/08/preview-and-crop-before-upload/

Files with following extensions are only allowed
        allowedExtensions: ['gif','jpg','jpeg','png','txt'],
        showCropTool: 1,
        sizeLimit: 10737418240, // Maximum filesize limit which works without any problems is 30MB. Current limit is set to 10MB = 10 * 1024 * 1024
        params: {
            'uploadedBy': 'Sapnagroup',
            'x1': '0',  // x coordinates of the image
            'y1': '0',      // x coordinates of the image
            'x2': '300',    // x coordinates of the image
            'y2': '150',    // y coordinates of the image
            'cWidth': '300',        // required crop width
            'cHeight': '150',       // required crop heignt
            'oWidth': '800',        // width of the crop preview image
            'oHeight': '600',       // height of the crop preview image
            'rWidth': '300',        // resize width
            'rHeight': '150'        // resize height
        },


Related Topics



Leave a reply



Submit