TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Resize Image Size using Canvas and Convert into Base64 Encoded String (Data URLs) and Blob in Javascript
Vivek Kumar
Apr 23
2016
Code
15.5
k
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
expand
Javascript code :
function
getBase64Image() {
var
filesSelected = document.getElementById(
"myFile"
).files;
if
(filesSelected.length > 0) {
var
file = filesSelected[0];
if
(file.type.match(
'image.*'
)) {
var
reader =
new
FileReader();
reader.readAsDataURL(file);
reader.onload =
function
(e) {
var
image =
new
Image();
image.onload =
function
(imageEvent) {
// Resize the image using canvas
var
canvas = document.createElement(
'canvas'
),
max_size = 300,
// TODO : max size for a pic
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);
//Getting base64 string;
var
dataUrl = canvas.toDataURL(
'image/jpeg'
);
//Getting blob data
RESIZED_IMAGE = dataURLToBlob(dataUrl);
}
image.src = e.target.result;
}
}
};
}
/* 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 */
UI Code
<input type=
"file"
id=
"myFile"
name=
"pic"
onchange=
"getBase64Image()"
accept=
"image/*"
>
image
base64 encoded string
data url
blob
javascript