基于asp.net实现图片在线上传并在线裁剪功能

yizhihongxing

下面是基于asp.net实现图片在线上传并在线裁剪功能的完整攻略:

1. 确定上传插件

为了实现在线上传图片,我们需要选择一个合适的上传插件。目前市场上比较流行的上传插件有uploadify和plupload,我们可以根据需求自行选择。

在这里,我以uploadify为例进行说明。

2. 实现图片上传

需先引入jquery、uploadify相关的js和css文件,然后在网页中加入一下代码:

<input type="file" name="file_upload" id="file_upload" />

再添加一下jquery脚本:

$(function() {
    $('#file_upload').uploadify({
        'swf'      : '/uploadify/uploadify.swf',
        'uploader' : '/upload.php'
    });
});

其中,'swf'表示flash文件路径,'uploader'表示处理上传请求的服务器文件路径。在服务器中,需要将上传的文件保存到web服务器上的某个文件夹以便后续裁剪操作。例如,我们可以在服务器端使用ASP.NET语言编写一个叫做upload.aspx的文件来处理上传请求。

以下是upload.aspx代码:

protected void Page_Load(object sender, EventArgs e)
{
    string path = Server.MapPath("~/upload/");//上传文件存储的路径
    if (!System.IO.Directory.Exists(path))//判断是否需要创建目录
    {
        System.IO.Directory.CreateDirectory(path);
    }
    HttpFileCollection files = Request.Files;//获取上传文件列表
    for (int i = 0; i < files.Count; i++)
    {
        HttpPostedFile file = files[i];
        string fileName = System.IO.Path.GetFileName(file.FileName);
        file.SaveAs(path + "/" + fileName);//保存文件到本地
    }
}

至此,图片上传功能成功实现。

3. 实现图片裁剪

接下来,我们需要引用Jcrop库来实现图片裁剪功能。Jcrop是一款强大的图片裁剪插件,支持多种裁剪模式和裁剪尺寸。我们只需要在需要裁剪的图片上添加以下代码即可:

<img src="test.jpg" id="cropbox" />

然后,添加以下jquery脚本:

$(function() {
    $('#cropbox').Jcrop({
        aspectRatio: 1, //裁剪比例为1:1
        onSelect: updateCoords //裁剪结束后会调用updateCoords函数
    });
});

function updateCoords(c)
{
    $('#x').val(c.x);
    $('#y').val(c.y);
    $('#w').val(c.w);
    $('#h').val(c.h);//更新表单中的数据
    $('#thumb').css({
        width: Math.round(100/c.w*$('#cropbox').width()) + 'px',
        height: Math.round(100/c.h*$('#cropbox').height()) + 'px',
        marginLeft: '-' + Math.round(100/c.w*c.x) + 'px',
        marginTop: '-' + Math.round(100/c.h*c.y) + 'px'//设置预览窗口中图片的尺寸和位置
    });
}

以上代码实现了裁剪框的生成,当用户选中裁剪区域后,会自动调用updateCoords函数,更新预览窗口中图片的尺寸和位置。

裁剪后,我们还需要通过服务器端将裁剪后的图片保存到本地。

以下是处理裁剪请求的代码:

protected void Page_Load(object sender, EventArgs e)
{
    int x = int.Parse(Request.Params["x"]);//获取裁剪区域的坐标和宽高尺寸
    int y = int.Parse(Request.Params["y"]);
    int w = int.Parse(Request.Params["w"]);
    int h = int.Parse(Request.Params["h"]);
    string imgPath = Server.MapPath("~/upload/test.jpg");//原始图片路径,从web.config文件中读取更佳
    string savePath = Server.MapPath("~/upload/thumb.jpg");//裁剪后保存的路径,从web.config文件中读取更佳
    FileStream fileStream = new FileStream(imgPath, FileMode.Open);//打开原始图片
    Image img = Image.FromStream(fileStream);//读取图片
    Bitmap bitmap = new Bitmap(w, h);//创建裁剪后保存的位图对象
    Graphics graphics = Graphics.FromImage(bitmap);//创建Graphics对象,用于绘制新图片
    graphics.DrawImage(img, new Rectangle(0, 0, w, h), new Rectangle(x, y, w, h), GraphicsUnit.Pixel);//绘制裁剪后新图片
    Bitmap result = new Bitmap(bitmap);//创建最终保存的位图对象
    result.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);//保存图片
    fileStream.Dispose();//释放资源
    img.Dispose();
    bitmap.Dispose();
    graphics.Dispose();
    result.Dispose();
}

至此,基于asp.net实现图片在线上传并在线裁剪功能的完整攻略就结束了。

示例说明

示例一

用户要上传一张图片到服务器,并将其裁剪成400*400的正方形。

<input type="file" name="file_upload" id="file_upload" />
<img src="" width="400" height="400" id="thumb" />
$(function() {
    $('#file_upload').uploadify({
        'swf'      : '/uploadify/uploadify.swf',
        'uploader' : '/upload.aspx',
        'onUploadComplete' : function(file) {
            $.ajax({
                url: '/crop.aspx',
                data: {
                    x: $('#x').val(),
                    y: $('#y').val(),
                    w: $('#w').val(),
                    h: $('#h').val()
                },
                success: function() {
                    $('#thumb').attr('src', '/upload/thumb.jpg');//上传完成后,裁剪图片并刷新预览窗口
                }
            });
        }
    });

    $('#cropbox').Jcrop({
        aspectRatio: 1,
        onSelect: updateCoords
    });

    function updateCoords(c)
    {
        $('#x').val(c.x);
        $('#y').val(c.y);
        $('#w').val(c.w);
        $('#h').val(c.h);
        $('#thumb').css({
            width: Math.round(100/c.w*$('#cropbox').width()) + 'px',
            height: Math.round(100/c.h*$('#cropbox').height()) + 'px',
            marginLeft: '-' + Math.round(100/c.w*c.x) + 'px',
            marginTop: '-' + Math.round(100/c.h*c.y) + 'px'
        });
    }
});
protected void Page_Load(object sender, EventArgs e)
{
    string path = Server.MapPath("~/upload/");
    if (!System.IO.Directory.Exists(path))
    {
        System.IO.Directory.CreateDirectory(path);
    }
    HttpFileCollection files = Request.Files;
    for (int i = 0; i < files.Count; i++)
    {
        HttpPostedFile file = files[i];
        string fileName = System.IO.Path.GetFileName(file.FileName);
        file.SaveAs(path + "/" + fileName);
    }
}
protected void Page_Load(object sender, EventArgs e)
{
    int x = int.Parse(Request.Params["x"]);
    int y = int.Parse(Request.Params["y"]);
    int w = int.Parse(Request.Params["w"]);
    int h = int.Parse(Request.Params["h"]);
    string imgPath = Server.MapPath("~/upload/test.jpg");
    string savePath = Server.MapPath("~/upload/thumb.jpg");
    FileStream fileStream = new FileStream(imgPath, FileMode.Open);
    Image img = Image.FromStream(fileStream);
    Bitmap bitmap = new Bitmap(w, h);
    Graphics graphics = Graphics.FromImage(bitmap);
    graphics.DrawImage(img, new Rectangle(0, 0, w, h), new Rectangle(x, y, w, h), GraphicsUnit.Pixel);
    Bitmap result = new Bitmap(bitmap);
    result.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
    fileStream.Dispose();
    img.Dispose();
    bitmap.Dispose();
    graphics.Dispose();
    result.Dispose();
}

示例二

用户要上传多张图片到服务器,并将其裁剪成200*200的正方形。

<input type="file" name="file_upload" id="file_upload" multiple="multiple" />
<ul id="thumbnails">
</ul>
$(function() {
    $('#file_upload').uploadify({
        'swf'      : '/uploadify/uploadify.swf',
        'uploader' : '/upload.aspx',
        'onUploadComplete' : function(file) {
            //上传完成后,按照顺序自动裁剪并刷新预览窗口
            $('#thumbnails').find('img').each(function(index) {
                var thumb = $(this);
                $.ajax({
                    url: '/crop.aspx',
                    data: {
                        x: thumb.data('x'),
                        y: thumb.data('y'),
                        w: thumb.data('w'),
                        h: thumb.data('h')
                    },
                    success: function() {
                        thumb.attr('src', '/upload/thumb' + index + '.jpg');
                    }
                });
            });
        }
    });

    $('#cropbox').Jcrop({
        aspectRatio: 1,
        onSelect: updateCoords
    });

    function updateCoords(c)
    {
        var thumb = $('<img>').attr({
            src: $('#cropbox').attr('src'),
            width: 200,
            height: 200
        }).data({
            x: c.x,
            y: c.y,
            w: c.w,
            h: c.h
        }).appendTo('#thumbnails');//在预览窗口中显示裁剪后的图片
    }
});
protected void Page_Load(object sender, EventArgs e)
{
    string path = Server.MapPath("~/upload/");
    if (!System.IO.Directory.Exists(path))
    {
        System.IO.Directory.CreateDirectory(path);
    }
    HttpFileCollection files = Request.Files;
    for (int i = 0; i < files.Count; i++)
    {
        HttpPostedFile file = files[i];
        string fileName = System.IO.Path.GetFileName(file.FileName);
        file.SaveAs(path + "/" + fileName);
    }
}
protected void Page_Load(object sender, EventArgs e)
{
    int x = int.Parse(Request.Params["x"]);
    int y = int.Parse(Request.Params["y"]);
    int w = int.Parse(Request.Params["w"]);
    int h = int.Parse(Request.Params["h"]);
    string imgPath = Server.MapPath("~/upload/test" + Request.Params["index"] + ".jpg");//index为图片编号,从0开始
    string savePath = Server.MapPath("~/upload/thumb" + Request.Params["index"] + ".jpg");
    FileStream fileStream = new FileStream(imgPath, FileMode.Open);
    Image img = Image.FromStream(fileStream);
    Bitmap bitmap = new Bitmap(w, h);
    Graphics graphics = Graphics.FromImage(bitmap);
    graphics.DrawImage(img, new Rectangle(0, 0, w, h), new Rectangle(x, y, w, h), GraphicsUnit.Pixel);
    Bitmap result = new Bitmap(bitmap);
    result.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
    fileStream.Dispose();
    img.Dispose();
    bitmap.Dispose();
    graphics.Dispose();
    result.Dispose();
}

在示例二中,预览窗口会按照顺序显示上传的多张图片的缩略图,并自动裁剪成200*200的正方形。裁剪操作结束后,会自动刷新预览窗口中的缩略图。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:基于asp.net实现图片在线上传并在线裁剪功能 - Python技术站

(0)
上一篇 2023年5月31日
下一篇 2023年5月31日

相关文章

  • C#中实现多继承的方法

    要在C#中实现多继承,可以使用以下两种方法:接口实现和类组合。 接口实现: 接口是一种约定协议,它定义了一组方法,类可以实现它们来达到特定的目的。我们可以定义多个接口,分别实现不同的方法,然后实现多个接口的类可以借助不同的方法来达成多重继承的目的。 示例代码如下: public interface IA { void methodA(); } public …

    C# 2023年6月7日
    00
  • C#串口通讯概念及简单的实现方法

    C#串口通讯概念及简单的实现方法 什么是串口通讯? 串口通讯是一种通过串行线(即一根数据线)来传输数据的通讯方式。在计算机领域,串口通讯常用于连接计算机和外部设备,如嵌入式设备,传感器等。在C#语言中,可以使用SerialPort类实现串口通讯功能。 SerialPort类的使用方法 在使用SerialPort类之前,需要引用System.IO.Ports命…

    C# 2023年6月7日
    00
  • Asp.net Mvc 身份验证、异常处理、权限验证(拦截器)实现代码

    Asp.net MVC 是一种基于 Model-View-Controller (MVC) 的 Web 应用程序框架。在开发 Asp.net MVC 应用程序时,实现身份验证、异常处理以及权限验证是非常必要的功能。下面,我们将分别介绍这三种功能的实现方法。 Asp.net MVC 身份验证实现 在 Asp.net MVC 中,实现身份验证有多种方法,包括 F…

    C# 2023年5月31日
    00
  • C#中的矩形数组(多维数组)和锯齿数组的实现

    关于C#中多维数组和锯齿数组的实现攻略,以下是详细的讲解。 多维数组 多维数组是一种包含多个维度的数组,形如一个表格,每行有多列,每列有多行。我们可以使用矩形数组或方形数组来表示。使用数组时,我们使用逗号来分隔不同的维度,例如int[,] array,其中[,]表示这个数组有两个维度。 矩形数组的实现 下面是一个基本的二维矩形数组的示例: int[,] ar…

    C# 2023年6月7日
    00
  • C# / VB.NET 在PPT中创建、编辑PPT SmartArt图形的方法详解

    C# / VB.NET 在PPT中创建、编辑PPT SmartArt图形的方法详解 什么是Office SmartArt? Office SmartArt 是微软Office套件中的一种图形类型,它可以帮助用户在较短的时间内创建具有高质量的信息图形。它的能力不仅限于流程图和组织结构图,还包括算法图、漏斗图、阶段图、矩阵图、金字塔图等不同种类的图形。 如何在C…

    C# 2023年6月3日
    00
  • .NET Core系列之MemoryCache 初识

    .NET Core系列之MemoryCache 初识 在本攻略中,我们将详细讲解.NET Core中的MemoryCache,包括其基本概念、使用方法和示例说明。 MemoryCache简介 MemoryCache是.NET Core中的一个内存缓存库,可以用于缓存应用程序中的数据。它提供了一种快速、可靠和高效的方式来缓存数据,以提高应用程序的性能和响应速度…

    C# 2023年5月16日
    00
  • C#编程总结(一)序列化总结

    下面是关于“C#编程总结(一)序列化总结”的完整攻略,包含两个示例。 1. 序列化总结 在C#编程中,序列化是将对象转换为可存储或可传输格式的过程。反序列化是将序列化的数据转换回对象的过程。C#提供了多种序列化方式,包括二进制序列化、XML序列化和JSON序列化等。以下是C#编程中序列化的总结: 1.1 二进制序列化 二进制序列化是将对象转换为二进制格式的过…

    C# 2023年5月15日
    00
  • c#中如何获取指定字符前的字符串

    在C#中获取指定字符(或字符串)前的字符串,可以采用String类的Substring和IndexOf方法来实现。 方法1:Substring方法 Substring方法是String类提供的一个获取子字符串的方法,可以通过指定起始位置和截取长度来获取指定范围的子字符串。我们可以通过查找指定字符(或字符串)的位置,然后取其前面的子串来获取需要的字符串。 示例…

    C# 2023年6月6日
    00
合作推广
合作推广
分享本页
返回顶部