用html5 canvas js 实现图片大小的压缩显示,图片上传后可在线预览。

本文介绍如何使用HTML5的Canvas和JavaScript编写一个图片压缩并在线预览的功能。通过创建HTML文件,定义CSS样式,以及编写JavaScript代码实现图片的选择、压缩、在Canvas上绘制和预览。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

网上查找了好多上传图片的代码,不过bug太多,还不如自己写一个。

首先创建一个html文件

代码如下:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>图片压缩--canvas</title>
</head>
<body>
<a class="file"><input type="file" id="fileElem" accept="image/*"  onchange="handleFiles(this)">选择</a>
<div class="canvas">
<p>
canvas:
</p>
<canvas id="canvas"></canvas>
</div>
<div id="fileList" class="img-wrap">

<p>
原图:
</p>
</div>
<div id="wrap">
<p>
压缩后:
</p>
</div>
</body>
</html>


创建相关的css代码如下:

.file {
    position: relative;
    display: inline-block;
    background: #D0EEFF;
    border: 1px solid #99D3F5;
    border-radius: 4px;
    padding: 4px 12px;
    overflow: hidden;
    color: #1E88C7;
    text-decoration: none;
    text-indent: 0;
    line-height: 20px;
}
.file input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
}
.file:hover {
    background: #AADFFD;
    border-color: #78C3F3;
    color: #004974;
    text-decoration: none;
}


需要引用的JS代码如下:

window.URL=window.URL||window.webkitURL;
var fileElem=document.getElementById("fileElem"); 
var fileList=document.getElementById("fileList");
var wrap=document.getElementById("wrap");
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");


canvas.width = 300;
canvas.height = 300;


function handleFiles(obj){

var files = obj.files,
img = new Image();

if(files.length > 0){
if(window.URL){
img.src = window.URL.createObjectURL(files[0]);
img.wwidth = 200;
img.onload=function(e){
window.URL.revokeObjectURL(this.src);

ctx.drawImage(img,0,0,canvas.width,canvas.width);

var imgend = new Image();
var dataurl  = canvas.toDataURL('image/png');
//Canvas转换为Blob对象
var blob = dataURLtoBlob(dataurl);

var url = window.URL.createObjectURL(blob);

imgend.onload = function() {
URL.revokeObjectURL(url);
};

console.log(imgend)
imgend.src=url;
imgend.id="imgend";
wrap.appendChild(imgend);
}
img.id="img1";
img.className="img1";
fileList.appendChild(img);


}
//opera不支持createObjectURL/revokeObjectURL方法。需要用FileReader对象来处理
else if(window.FileReader){
var reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = function(e){
alert(files[0].name+","+e.total+"bytes");
img.src = this.result;
img.width = 200;
fileList.appendChile(img);
}
}
}

}


function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type:mime});
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值