如何将前端压缩的图片保存到本地

stevenjin 2018-10-07 11:51:49
前端将图片压缩之后,怎样点击“确认按钮”后将该图保存到本地的磁盘中去?

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="CutImg.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>html5前端图片压缩</title>
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta http-equiv="Cache-Control" content="no-cache" />
<meta name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=0" />
<meta content="telephone=no" name="format-detection" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

<script type="text/javascript">
/**
* 图片压缩,大仙造
* @param fil
* @param id
*/
function getUrl(fil, id) {
var Cnv = document.getElementById('myCanvas');
var Cntx = Cnv.getContext('2d');//获取2d编辑容器
var imgss = new Image();
var agoimg = document.getElementById("ago");
for (var intI = 0; intI < fil.length; intI++) {
var tmpFile = fil[intI];
var reader = new FileReader();
reader.readAsDataURL(tmpFile);
reader.onload = function (e) {
url = e.target.result;
imgss.src = url;
agoimg.src = url;
agoimg.onload = function () {
//等比缩放
var m = imgss.width / imgss.height;
Cnv.height = 300;//该值影响缩放后图片的大小
Cnv.width = 300 * m;
//img放入画布中
//设置起始坐标,结束坐标
Cntx.drawImage(agoimg, 0, 0, 300 * m, 300);
}
}
}
}


function pressss() {//
//获取canvas压缩后的图片数据
var Pic = document.getElementById("myCanvas").toDataURL("image/png");
var imgs = document.getElementById("press");
imgs.src = Pic;
//上传
// 去除多余,得到base64编码的图片字节流
Pic = Pic.replace(/^data:image\/(png|jpg);base64,/, "");
//可以用ajax提交到后台,提交后可以直接存数据库,也可以保存成图片,此处略,
//技术交流495120021
//
}
</script>
</head>
<body>
<form runat="server">
<div>
<input type="file" runat="server" id="fileId" name="fileId" onchange="getUrl(this.files,this.id);"/>
</div>
<canvas id="myCanvas" style="display: none"></canvas>
old img-><img src="" alt="" id="ago" style="width: 500px;" />
<input type="button" value="ya suo->" onclick="pressss()" />
new img-><img src="" alt="" runat="server" id="press" />

<asp:Button ID="btnSubmit" Text=" 确 认 添 加 " runat="server" class="btn btn-primary active pull-right" OnClick="btnSubmit_Click"/>
</form>

</body>
</html>
...全文
493 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
stevenjin 2018-10-08
  • 打赏
  • 举报
回复
2.后台
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CutImg
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string str = HttpContext.Current.Request["title"];
            HttpPostedFile rq = Request.Files["imagefile"];
            if (rq!=null)
            {                
                Bitmap nImage = new Bitmap(rq.InputStream);
                string fileName = Guid.NewGuid().ToString().Replace("-", "") + ".png";//获取文件名
                string filePath = Server.MapPath(@"~\UploadImages\");

                //路径不存在则创建
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                nImage.Save(filePath+fileName);               
            }
           
        }

        private void Base64StringToImage(string inputStr)
        {
           
           
            if (string.IsNullOrWhiteSpace(inputStr))
                return;
            try
            {
               
               
                string filePath = "E:\\bb.jpg";
                byte[] arr = Convert.FromBase64String(inputStr.Substring(inputStr.IndexOf("base64,") + 7).Trim('\0'));
                using (MemoryStream ms = new MemoryStream(arr))
                {
                    Bitmap bmp = new Bitmap(ms);
                    //新建第二个bitmap类型的bmp2变量。
                    Bitmap bmp2 = new Bitmap(bmp, bmp.Width, bmp.Height);
                    //将第一个bmp拷贝到bmp2中
                    Graphics draw = Graphics.FromImage(bmp2);
                    draw.DrawImage(bmp, 0, 0);
                    draw.Dispose();
                    bmp2.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    ms.Close();
                }

            }
            catch (Exception ex)
            {

            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {

        }
    }
}
stevenjin 2018-10-08
  • 打赏
  • 举报
回复
参照前辈的指点,这样实现了。失真很少,只是后台自己写的方式有些欠妥,请指正! 1.前台
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="CutImg.WebForm1" %>

<!DOCTYPE html>

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <title>移动端图片压缩上传demo</title>
  <style>
    *{margin: 0;padding: 0;}
    li{list-style-type: none;}
    a,input{outline: none;-webkit-tap-highlight-color:rgba(0,0,0,0);}
    #choose{display: none;}
    canvas{width: 100%;border: 1px solid #000000;}
    #upload{display: block;margin: 10px;height: 60px;text-align: center;line-height: 60px;border: 1px solid;border-radius: 5px;cursor: pointer;}
    .touch{background-color: #ddd;}
    .img-list{margin: 10px 5px;}
    .img-list li{position: relative;display: inline-block;width: 100px;height: 100px;margin: 5px 5px 20px 5px;border: 1px solid rgb(100,149,198);background: #fff no-repeat center;background-size: cover;}
    .progress{position: absolute;width: 100%;height: 20px;line-height: 20px;bottom: 0;left: 0;background-color:rgba(100,149,198,.5);}
    .progress span{display: block;width: 0;height: 100%;background-color:rgb(100,149,198);text-align: center;color: #FFF;font-size: 13px;}
    .size{position: absolute;width: 100%;height: 15px;line-height: 15px;bottom: -18px;text-align: center;font-size: 13px;color: #666;}
    .tips{display: block;text-align:center;font-size: 13px;margin: 10px;color: #999;}
    .pic-list{margin: 10px;line-height: 18px;font-size: 13px;}
    .pic-list a{display: block;margin: 10px 0;}
    .pic-list a img{vertical-align: middle;max-width: 30px;max-height: 30px;margin: -4px 0 0 10px;}
  </style>
</head>
<body>
<input type="file" id="choose" accept="image/*" multiple>
<ul class="img-list"></ul>
<a id="upload">上传图片</a>
<span class="tips">只允许上传jpg、png及gif</span>
<div class="pic-list">
  你上传的图片(图片有效期为1分钟):
</div>

<script src="jquery-1.10.2.min.js"></script>
<script>
    var filechooser = document.getElementById("choose");
    //    用于压缩图片的canvas
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext('2d');
    //    瓦片canvas
    var tCanvas = document.createElement("canvas");
    var tctx = tCanvas.getContext("2d");
    var maxsize = 100 * 1024;
    $("#upload").on("click", function () {
        filechooser.click();
    })
        .on("touchstart", function () {
            $(this).addClass("touch")
        })
        .on("touchend", function () {
            $(this).removeClass("touch")
        });
    filechooser.onchange = function () {
        if (!this.files.length) return;
        var files = Array.prototype.slice.call(this.files);
        if (files.length > 9) {
            alert("最多同时只可上传9张图片");
            return;
        }
        files.forEach(function (file, i) {
            if (!/\/(?:jpeg|png|gif)/i.test(file.type)) return;
            var reader = new FileReader();
            var li = document.createElement("li");
            //          获取图片大小
            var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB";
            li.innerHTML = '<div class="progress"><span></span></div><div class="size">' + size + '</div>';
            $(".img-list").append($(li));
            reader.onload = function () {
                var result = this.result;
                var img = new Image();
                img.src = result;
                $(li).css("background-image", "url(" + result + ")");
                //如果图片大小小于100kb,则直接上传
                if (result.length <= maxsize) {
                    img = null;
                    upload(result, file.type, $(li));
                    return;
                }
                //      图片加载完毕之后进行压缩,然后上传
                if (img.complete) {
                    callback();
                } else {
                    img.onload = callback;
                }
                function callback() {
                    var data = compress(img);
                    upload(data, file.type, $(li));
                    img = null;
                }
            };
            reader.readAsDataURL(file);
        })
    };
    //    使用canvas对大图片进行压缩
    function compress(img) {
        var initSize = img.src.length;
        var width = img.width;
        var height = img.height;
        //如果图片大于四百万像素,计算压缩比并将大小压至400万以下
        var ratio;
        if ((ratio = width * height / 4000000) > 1) {
            ratio = Math.sqrt(ratio);
            width /= ratio;
            height /= ratio;
        } else {
            ratio = 1;
        }
        canvas.width = width;
        canvas.height = height;
        //        铺底色
        ctx.fillStyle = "#fff";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        //如果图片像素大于100万则使用瓦片绘制
        var count;
        if ((count = width * height / 1000000) > 1) {
            count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
            //            计算每块瓦片的宽和高
            var nw = ~~(width / count);
            var nh = ~~(height / count);
            tCanvas.width = nw;
            tCanvas.height = nh;
            for (var i = 0; i < count; i++) {
                for (var j = 0; j < count; j++) {
                    tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
                    ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
                }
            }
        } else {
            ctx.drawImage(img, 0, 0, width, height);
        }
        //进行最小压缩
        var ndata = canvas.toDataURL('image/jpeg', 0.1);
        console.log('压缩前:' + initSize);
        console.log('压缩后:' + ndata.length);
        console.log('压缩率:' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
        tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
        return ndata;
    }
    //    图片上传,将base64的图片转成二进制对象,塞进formdata上传
    function upload(basestr, type, $li) {
        var text = window.atob(basestr.split(",")[1]);
        var buffer = new Uint8Array(text.length);
        var pecent = 0, loop = null;
        for (var i = 0; i < text.length; i++) {
            buffer[i] = text.charCodeAt(i);
        }
        var blob = getBlob([buffer], type);
        var xhr = new XMLHttpRequest();
        var formdata = getFormData();
        formdata.append('title', 'ok');
        alert(blob);
        formdata.append('imagefile', blob);
        xhr.open('post', 'WebForm1.aspx');
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var jsonData = JSON.parse(xhr.responseText);
                var imagedata = jsonData[0] || {};
                var text = imagedata.path ? '上传成功' : '上传失败';
                console.log(text + ':' + imagedata.path);
                clearInterval(loop);
                //当收到该消息时上传完毕
                $li.find(".progress span").animate({ 'width': "100%" }, pecent < 95 ? 200 : 0, function () {
                    $(this).html(text);
                });
                if (!imagedata.path) return;
                $(".pic-list").append('<a href="' + imagedata.path + '">' + imagedata.name + '(' + imagedata.size + ')<img src="' + imagedata.path + '" /></a>');
            }
        };
        //数据发送进度,前50%展示该进度
        xhr.upload.addEventListener('progress', function (e) {
            if (loop) return;
            pecent = ~~(100 * e.loaded / e.total) / 2;
            $li.find(".progress span").css('width', pecent + "%");
            if (pecent == 50) {
                mockProgress();
            }
        }, false);
        //数据后50%用模拟进度
        function mockProgress() {
            if (loop) return;
            loop = setInterval(function () {
                pecent++;
                $li.find(".progress span").css('width', pecent + "%");
                if (pecent == 99) {
                    clearInterval(loop);
                }
            }, 100)
        }
        xhr.send(formdata);
    }
    /**
     * 获取blob对象的兼容性写法
     * @param buffer
     * @param format
     * @returns {*}
     */
    function getBlob(buffer, format) {
        try {
            return new Blob(buffer, { type: format });
        } catch (e) {
            var bb = new (window.BlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder);
            buffer.forEach(function (buf) {
                bb.append(buf);
            });
            return bb.getBlob(format);
        }
    }
    /**
     * 获取formdata
     */
    function getFormData() {
        var isNeedShim = ~navigator.userAgent.indexOf('Android')
            && ~navigator.vendor.indexOf('Google')
            && !~navigator.userAgent.indexOf('Chrome')
            && navigator.userAgent.match(/AppleWebKit\/(\d+)/).pop() <= 534;
        return isNeedShim ? new FormDataShim() : new FormData()
    }
    /**
     * formdata 补丁, 给不支持formdata上传blob的android机打补丁
     * @constructor
     */
    function FormDataShim() {
        console.warn('using formdata shim');
        var o = this,
            parts = [],
            boundary = Array(21).join('-') + (+new Date() * (1e16 * Math.random())).toString(36),
            oldSend = XMLHttpRequest.prototype.send;
        this.append = function (name, value, filename) {
            parts.push('--' + boundary + '\r\nContent-Disposition: form-data; name="' + name + '"');
            if (value instanceof Blob) {
                parts.push('; filename="' + (filename || 'blob') + '"\r\nContent-Type: ' + value.type + '\r\n\r\n');
                parts.push(value);
            }
            else {
                parts.push('\r\n\r\n' + value);
            }
            parts.push('\r\n');
        };
        // Override XHR send()
        XMLHttpRequest.prototype.send = function (val) {
            var fr,
                data,
                oXHR = this;
            if (val === o) {
                // Append the final boundary string
                parts.push('--' 

62,041

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧