AUTHOR: Peter Milchev
DATE POSTED: December 11, 2018
Resize images on client-side before uploading them with the RadAsyncUpload control.
Being able to intercept the uploading process and modifying the file, we would need to override the private _uploadFile method of the AsyncUpload's upload module.
Then, for the HTML5 resize, we would use a Canvas as demonstrated below:
<script>
//https://stackoverflow.com/questions/10333971/html5-pre-resize-images-before-uploading
//https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images
//https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob
//https://stackoverflow.com/questions/27159179/how-to-convert-blob-to-file-in-javascript
function
pageLoadHandler() {
var
asyncupload = $find(
"<%= RadAsyncUpload1.ClientID %>"
);
old_uploadFile = asyncupload._uploadModule._uploadFile;
asyncupload._uploadModule._uploadFile =
(pair) {
uploadFile = pair.file;
img = document.createElement(
"img"
canvas = document.createElement(
"canvas"
reader =
new
FileReader();
reader.onload =
(e) {
img.src = e.target.result
img.onload =
() {
ctx = canvas.getContext(
"2d"
ctx.drawImage(img, 0, 0);
MAX_WIDTH = 400;
MAX_HEIGHT = 100;
width = img.width;
height = img.height;
if
(width > height) {
(width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
else
{
(height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob(
(blob) {
blob.lastModifiedDate =
Date();
blob.name =
"mynewimage.jpg"
;
pair.file = blob;
old_uploadFile.call(
this
, pair)
},
'image/jpeg'
, 1);
reader.readAsDataURL(uploadFile);
// Sys.Application.remove_load(pageLoadHandler);
Sys.Application.add_load(pageLoadHandler);
</script>
<
telerik:RadAsyncUpload
runat
=
"server"
ID
"RadAsyncUpload1"
></
>
Resources Buy Try