Это должно поддерживать как изображение, так и видео.Это создаст миниатюру для мультимедиа, но также сохранит соотношение сторон мультимедиа.
Это также должно привести в порядок после себя, чтобы не происходило утечек событийЭто также сгладит уменьшенное изображение.
/* example to resize an image to 300px width
and keep the aspect */
resizeMedia('/images/logo.jpg', 300, function(data)
{
console.log(data); // the new thumbnail data uri
});
/* this will create a thumbnail of an image or video
and keep the aspect.
@param (string | object) media = the image string or video object
@param (int) width = the new width to contain the media
@param (function) callBack = the callBack to handle the
image data uri */
function resizeMedia(media, width, callBack)
{
var self = this;
/* this will get the type by checking ifthe media
is a string (e.g. img src or dataUri) */
var type = typeof media === 'string'? 'image' : 'video';
/* this will get the height and width of the resized
media and keep the aspect.
@param (int) udateSize = the width the modify
@param (int) width = the old width
@param (int) height = the old height
@return (object) the width and height to modify the
media */
var getModifySize = function(updateSize, width, height)
{
var getModifyAspect = function(max, min, value)
{
var ratio = max / min;
return value * ratio;
};
return {
width: updateSize,
height: getModifyAspect(updateSize, width, height)
};
};
/* this will create a canvas and draw the media
on the canvas.
@param (object) media = the image or video
object
@param (int) width = the canvas width
@param (int) height = the canvas height
@return (object) the new canvas */
var createCanvas = function(media, width, height)
{
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
ctx.mozImageSmoothingEnabled = true;
ctx.webkitImageSmoothingEnabled = true;
ctx.msImageSmoothingEnabled = true;
ctx.imageSmoothingEnabled = true;
/* we need to draw on load to make sure
the image is ready to be used */
ctx.drawImage(media, 0, 0, width, height);
/* this will convert the canvas to a data uri
using jpeg to speed up the process. if you need
to keep transparency remove the mime type
and it will default to png */
callBack(canvas.toDataURL('image/jpeg'));
return canvas;
};
if(type === 'image')
{
var img = new window.Image();
img.crossOrigin = "anonymous";
img.addEventListener('load', function loadImage()
{
var modify = getModifySize(width, img.width, img.height);
createCanvas(img, modify.width, modify.height);
img.removeEventListener('load', loadImage);
});
img.src = media;
}
else if(type === 'video')
{
var modify = getModifySize(width, media.videoWidth, media.videoHeight);
createCanvas(media, modify.width, modify.height);
}
};