我需要在客户端调整图像大小,然后在提交之前将其添加到表单中。
这是完整的html:
<html>
<body>
<form action="url">
<label><b>Avatar image:</b></label>
<input type="file" id="imageLoader" name="avatar" onchange="return ShowImagePreview( this, 0 );" /><br />
<canvas id="imageCanvas" class="previewcanvas" width="133" height="100"></canvas>
<br />
<input type="submit" value="Save" />
</form>
<script>
var imageLoader = document.getElementById('imageLoader');
function HandleFileEvent( event, selection )
{
var img = new Image;
img.onload = function( event ) { UpdatePreviewCanvas( event, img, selection ) }
img.src = event.target.result;
}
function ShowImagePreview( object, selection )
{
if( typeof object.files === "undefined" )
return;
var files = object.files;
if( !( window.File && window.FileReader && window.FileList && window.Blob ) )
{
alert('The File APIs are not fully supported in this browser.');
return false;
}
if( typeof FileReader === "undefined" )
{
alert( "Filereader undefined!" );
return false;
}
var file = files[0];
if( file !== undefined && file != null && !( /image/i ).test( file.type ) )
{
alert( "File is not an image." );
return false;
}
reader = new FileReader();
reader.onload = function( event ) { HandleFileEvent( event, selection ) }
reader.readAsDataURL( file );
}
function UpdatePreviewCanvas( event, img, selection )
{
var canvas = document.getElementById('imageCanvas');
var context = canvas.getContext( '2d' );
var world = new Object();
world.width = canvas.offsetWidth;
world.height = canvas.offsetHeight;
canvas.width = world.width;
canvas.height = world.height;
var WidthDif = img.width - world.width;
var HeightDif = img.height - world.height;
var Scale = 0.0;
if( WidthDif > HeightDif )
{
Scale = world.width / img.width;
}
else
{
Scale = world.height / img.height;
}
if( Scale > 1 )
Scale = 1;
var UseWidth = Math.floor( img.width * Scale );
var UseHeight = Math.floor( img.height * Scale );
var x = Math.floor( ( world.width - UseWidth ) / 2 );
var y = Math.floor( ( world.height - UseHeight ) / 2 );
context.drawImage( img, x, y, UseWidth, UseHeight );
}
</script>
</body>
</html>
我想到的是将图像放到画布上,但我不知道如何将它带回输入。
(使用此link)
答案 0 :(得分:1)
您可以使用扩展版本的drawImage来调整原始图片的大小。
扩展版本从[0,0]和img.width x img.height拉出完整的原始图像。
然后缩放原始图像并在画布上以[0,0]
绘制缩放版本context.drawImage( img, 0,0,img.width,img.height, 0,0,UseWidth,UseHeight );